String index out of range:-1

问题描述:

String index out of range:-1
1个回答 分类:综合 2014-11-02

问题解答:

我来补答
给你举一个简单的例子,讲解方法indexOf(int ch)
源文件Test.java
public class Test {
public static void main(String args[])
{
String str1="aacdabcd";
String str2="abcdabcd";
System.out.println(str1.indexOf(98));
System.out.println(str2.indexOf(98));
}
}
运行结果是5和1.
indexOf(int ch)方法的作用是字符在此字符串中第一次出现处的索引..整型(int)数据它会转换成字符型(char),例中的98对应的是字符'b',字符'b'在字符串str1中第一次出现处是第5个位置(不是第6个,因为是从0开始计算的,这个应该知道吧),在字符串str2中第一次出现处是第1个位置.
其实实参98换成'b',运行结果是一样的.换成101则返回-1,101对应的是字符'e',字符串str1,str2中没有字符'e',方法返回的值是-1..
 
 
展开全文阅读
剩余:2000