Java函数:如何在字符串中查找一个子字符串并返回位置?
发布时间:2023-06-22 06:28:41
在Java中,查找一个子字符串的方法是使用String类的indexOf方法。这个方法接受一个字符串参数,并返回它在调用方法的字符串中出现的 个位置。
例如,考虑下面的代码:
String str = "Hello, world!";
int pos = str.indexOf("world");
System.out.println(pos);
在这个例子中,我们使用indexOf方法查找字符串"world"在str的位置。它返回6,因为"world"出现在第七个字符处,从0开始计数。
如果指定的字符串不在字符串中,indexOf方法将返回-1。例如,以下代码显示了如何检查一个字符串是否包含另一个字符串:
String str1 = "Hello, world!";
String str2 = "world";
if (str1.indexOf(str2) != -1) {
System.out.println(str2 + " is found in " + str1);
} else {
System.out.println(str2 + " is not found in " + str1);
}
在这个例子中,如果str1包含str2,就会打印"world is found in Hello, world!"。
如果要查找指定子字符串的所有出现位置,则可以使用indexOf的重载版本。以下代码显示了如何使用该方法查找所有匹配项:
String str = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?";
String sub = "wood";
int pos = str.indexOf(sub);
while (pos != -1) {
System.out.println(sub + " found at position " + pos);
pos = str.indexOf(sub, pos + sub.length());
}
在这个例子中,我们使用了indexOf的重载版本,该版本接受两个参数, 个参数是要查找的子字符串,第二个参数是从哪个位置开始查找。我们使用循环来找到所有匹配项,并不断更新pos以便在每次循环迭代中查找下一个匹配项。
