Java中字符串indexof() 的使用方法

来源:互联网 发布:2016总决赛数据 编辑:程序博客网 时间:2024/06/16 12:19

转载地址:http://blog.csdn.net/qq_27093465/article/details/51832189


Java中字符串中子串的查找共有四种方法,如下:
1、int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。 
2、int indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。 
3、int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。 
4、int lastIndexOf(String str, int startIndex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。

[java] view plain copy
  1. public class Test {  
  2.     public static void main(String[] args) {  
  3.         String s = "xXccxxxXX";  
  4.         // 从头开始查找是否存在指定的字符         //结果如下   
  5.         System.out.println(s.indexOf("c"));     //2  
  6.         // 从第四个字符位置开始往后继续查找,包含当前位置  
  7.         System.out.println(s.indexOf("c"3));  //3  
  8.         //若指定字符串中没有该字符则系统返回-1  
  9.         System.out.println(s.indexOf("y"));     //-1  
  10.         System.out.println(s.lastIndexOf("x")); //6  
  11.     }  
  12. }

原创粉丝点击