在Java中,indexOf
是一个字符串(String
)类的方法,用于查找子字符串在原字符串中首次出现的位置。如果找到了子字符串,则返回其在原字符串中的起始索引(从0开始计数);如果没有找到,则返回-1。
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
str
:要查找的子字符串。fromIndex
(可选):开始查找的位置。public class Main {
public static void main(String[] args) {
String text = "Hello, world!";
String search = "world";
// 查找子字符串 "world" 在 text 中的位置
int index = text.indexOf(search);
if (index != -1) {
System.out.println("子字符串 \"" + search + "\" 在位置 " + index + " 处找到。");
} else {
System.out.println("子字符串 \"" + search + "\" 未找到。");
}
}
}
子字符串 "world" 在位置 7 处找到。
indexOf
可能会影响性能。indexOf
是大小写敏感的。String lowerCaseText = text.toLowerCase();
int indexIgnoreCase = lowerCaseText.indexOf(search.toLowerCase());
通过这种方式,可以确保搜索操作不受大小写影响。
总之,indexOf
方法在Java中是一个非常实用的工具,适用于多种文本处理场景。
领取专属 10元无门槛券
手把手带您无忧上云