Java中indexOf的用法


indexOf有四種用法:

1.indexOf(int ch) 在給定字符串中查找字符(ASCII),找到返回字符數組所對應的下標找不到返回-1

2.indexOf(String str)在給定符串中查找另一個字符串。。。

3.indexOf(int ch,int fromIndex)從指定的下標開始查找某個字符,查找到返回下標,查找不到返回-1

4.indexOf(String str,int fromIndex)從指定的下標開始查找某個字符串。。。

public class Test {

	public static void main(String[] args) {
		char[] ch= {'a','b','c','h','e','l','l','o'};
		String str=new String(ch);

		//1.indexOf(int ch)
		str.indexOf(104);
		System.out.println(str.indexOf(104));//h所在下標為3

		//2.indexOf(String str)
		str.indexOf("hell");
		System.out.println(str.indexOf("hell"));//3

		//3.indexOf(int ch,int fromIndex)
		str.indexOf(101, 4);//4
		System.out.println(str.indexOf(101, 4));
		str.indexOf(101,5);//沒有查找到返回-1
		System.out.println(str.indexOf(101,5));

		//4.indexOf(String str,int fromIndex)
		str.indexOf("che", 0);//等價於str.indexOf("che")
		System.out.println(str.indexOf("che", 0));//2
	}
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM