indexOf()方法返回的是搜索的字符串或字符串中首次出现的索引位置,如果没有检索到要查找的字符或字符串,则返回-1。
语法如下:
a.indexof(substr);
// a:任意字符串对象
// substr:要搜索的字符或字符串
例如,查找字符e在字符串str中首次出现的索引位置,代码如下:
String str="We are the world";
int size=str.indexof('e');
实例:判断字符串中是否有中文逗号
创建StringIndexOf()类,判断字符串“明月几时有,把酒问青天”。中是否存在中文逗号。
代码如下:
public class StringIndexOf {
public static void main(String[] args)
String str = "明月几时有,把酒问青天。"; //创建字符串对象
//获取字符串中文逗号首次出现的索引,赋值给charIndex
int charIndex = str.indexof(“ , ”);
if(charIndex! = -1){ // 判断:index的值不等于-1
//如果index不等于-1,则执行此代码,说明字符串中有中文逗号
System.out.println("字符串中中文逗号的索引为:" + charIndex);
}else{ //如果index等于-1,则执行此行代码,说明字符串中没有中文逗号
System.out.println("字符串中没有中文逗号");
}
}
}