Java 中 String的indexOf 的用法
2013-09-11 09:58 totokaka 阅读(1003) 评论(0) 收藏 举报indexOf() 方法
返回 String 对象内第一次出现子字符串的字符位置。如果此字符串中没有这样的字符,则返回 -1。
提示和注释
注释:indexOf() 方法对大小写敏感!
注释:如果要检索的字符串值没有出现,则该方法返回 -1。
注释:java的集合类中也有indexof方法,Collection<T>.indexof().使用方法类似。
借用网友的例子,拿来备存使用
String.indexOf函数用法小结
1. indexOf的参数是String, startIndex: Number;
indexOf的返回值为int,
2. Function indexOf 包含如下几个格式:
1). Strng.indexOf(substring) //搜索String中的substring,默认从0位开始;
2). String.indexOf(substring, int m) //搜索String中的substring, 默认从第m位开始;
1). Strng.indexOf(substring) //搜索String中的substring,默认从0位开始;
2). String.indexOf(substring, int m) //搜索String中的substring, 默认从第m位开始;
下面来个例子
1 public class Hehe 2 { 3 4 5 int i; 6 int x; 7 String ip= null; 8 String input1 = null; 9 String input2 = null; 10 public void main(String args[]){ 11 ip = "126.168.1.1"; 12 i = ip.indexOf('.'); 13 x = ip.indexOf('.',i+1); 14 input1 = ip.substring(0,i); 15 input2 = ip.substring(i+1, x); 16 17 System.out.println("the input1 is "+input1); 18 System.out.println("the input2 is "+input2); 19 } 20 }
结果是
the input1 is 126
the input2 is 168
the input2 is 168