介绍
在本实验中,我们将学习如何在 Java 字符串中查找单词或子字符串。我们将使用 String 类的 indexOf()
和 contains()
方法来定位给定字符串中的子字符串。
在本实验中,我们将学习如何在 Java 字符串中查找单词或子字符串。我们将使用 String 类的 indexOf()
和 contains()
方法来定位给定字符串中的子字符串。
让我们创建一个 Java 文件,用于编写 Java 代码。打开终端并使用以下命令创建 Java 文件:
touch ~/project/FindWordInString.java
这里,FindWordInString
是我们的 Java 文件的名称。
indexOf()
方法在字符串中查找单词在这一步中,我们将使用 indexOf()
方法来查找指定子字符串在给定字符串中的索引。如果子字符串存在于字符串中,则返回其起始索引,否则返回 -1。
public class FindWordInString {
public static void main(String[] args) {
String str = "This sentence contains the word find me";
System.out.println(str);
String find = "find me";
int index = str.indexOf(find);
if (index >= 0) {
System.out.println("Word found at index: " + index);
} else {
System.out.println("Word not found");
}
}
}
使用以下命令运行代码:
javac FindWordInString.java && java FindWordInString
你应该会看到如下输出:
This sentence contains the word find me
Word found at index: 31
contains()
方法在字符串中查找单词在这一步中,我们将使用 contains()
方法来检查给定字符串是否包含指定的子字符串。如果包含,则返回 true,否则返回 false。
public class FindWordInString {
public static void main(String[] args) {
String str = "This sentence contains the word find me";
System.out.println(str);
String find = "find me";
boolean found = str.contains(find);
if (found) {
System.out.println("Word found");
} else {
System.out.println("Word not found");
}
}
}
使用以下命令运行代码:
javac FindWordInString.java && java FindWordInString
你应该会看到如下输出:
This sentence contains the word find me
Word found
在本实验中,我们学习了如何使用 indexOf()
和 contains()
方法在 Java 字符串中查找单词或子字符串。我们创建了一个 Java 文件并编写了 Java 代码来查找给定字符串中的子字符串。我们还学习了如何在 Ubuntu 中使用命令行运行 Java 代码。