当前位置:编程学习 > JSP >>

java indexOf() lastIndexOf() 字符串查找函数

利用indexOf()匹配字符串

返回 String 对象内第一次出现子字符串的字符位置。

strObj.indexOf(subString[, startIndex])
参数
strObj
必选项。String 对象或文字。
subString
必选项。要在 String 对象中查找的子字符串。
starIndex
可选项。该整数值指出在 String 对象内开始查找的索引。如果省略,则从字符串的开始处查找。
说明
indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回 -1。

如果 startindex 是负数,则 startindex 被当作零。如果它比最大的字符位置索引还大,则它被当作最大的可能索引。

 

public class MainClass{

  public static void main(String[] arg){
    String str = "abcde";
   
    int index = 0;       
    index = str.indexOf('c'); 

    System.out.println(index);
  }

}


实例二

public class MainClass{

  public static void main(String[] arg){
    String str = "abcdea";
   
    int index = 0;       
    index = str.lastIndexOf('a');        

    System.out.println(index);
  }

}

搜索指定字符所在字符串中的位置

public class MainClass{

  public static void main(String[] arg){
    String str = "abcdea";
    int startIndex = 3;
   
    int index = 0;       
    index = str.indexOf('a', startIndex);        

    System.out.println(index);
  }

}

字符串最后面出来

public   int   lastIndexOf(String   str,   int   fromIndex)  
//从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。
//   k   <=   Math.min(fromIndex,   str.length())   &&   this.startsWith(str,   k)
//   就是在String中查找str出现的最后一次位置!如果位置 <=fromIndex就返回,否则返回-1
对你的情景就是:
//   banner中最后一次出现One的位置在9
//并且9 <10所以返回9

public class MainClass{

  public static void main(String[] arg){
    String str = "abcdeabcdef";
  
    int index = 0;       
    index = str.lastIndexOf("ab");        

    System.out.println(index);
  }

}

补充:Jsp教程,Java基础 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,