Java中indexof()的使用

Java中字符串中子串的查找共有四种方法(indexof())
indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。
如果 startindex 是负数,则 startindex 被当作零。如果它比最大的字符位置索引还大,则它被当作最大的可能索引。


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) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。

public class Person {
    public static void main(String[] args) {

    	String string="dccgcfacggx";
    	//返回第一次出现的指定子字符串在此字符串中的索引。
    	System.out.println(string.indexOf("c"));//结果:1
    	
       	//如果没有找到子字符串,则返回-1
    	System.out.println(string.indexOf("z"));//结果:-1
    	
    	//从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。 
    	System.out.println(string.indexOf("c",3));//结果:4
    	
    	//返回在此字符串中最右边出现的指定子字符串的索引。
    	System.out.println(string.lastIndexOf("g"));//结果:9
    	
    	//从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。
    	System.out.println(string.lastIndexOf("g",8));//结果:8
     }
}

猜你喜欢

转载自blog.csdn.net/yilihuang/article/details/80780345