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