在计算机中,String对象是用数组表示的,所以才有了字符串下标。
public class StringIndexOf {
public static void main(String[] args) {
String str = "明月几时有,把酒问青天。";//创建字符串对象
//获取字符串中文逗号首次出现的索引,赋值给charIndex
int charIndex = str.indexOf(",");
if(charIndex != -1) {
//如果index不等于-1,则执行此行代码,说明字符串中有中文逗号
System.out.println("字符串中中文逗号的索引为:"+ charIndex);
}else {//如果index等于-1,则执行此行代码,说明字符串中没有中文逗号
System.out.println("字符串中没有中文逗号");
}
}
}
**补充:**index()方法返回的是搜索的字符或字符串在字符窜中首次出现的索引位置,如果没有检索到要查找的字符或字符串,则返回-1。
a.indexOf(substr);//a:任意字符串对象 substr:要搜索的字符或字符串