JAVA——String类indexOf()和substring()用法详解


indexOf()的四种用法

indexOf(int ch)
返回指定字符在此字符串中第一次出现处的索引,未找到返回-1。
例如

String str1="01234543210";
char ch='2';
System.out.println( str1.indexOf(ch) );

输出结果:2
indexOf(int ch, int fromIndex)
从指定的索引开始搜索,返回指定字符在此字符串中第一次出现处的索引,未找到返回-1。
例如

String str1="01234543210";
char ch='2';
System.out.println( str1.indexOf(ch,4));

输出结果:8
indexOf(String str)
返回指定字符串在此字符串中第一次出现处的索引,未找到返回-1。
例如

String str1="012345012345";
String str2="123";
System.out.println( str1.indexOf(str2));

输出结果:1
indexOf(String str, int fromIndex)
从指定的索引开始搜索,返回指定字符串在此字符串中第一次出现处的索引,未找到返回-1。
例如

String str1="012345012345";
String str2="123";
System.out.println( str1.indexOf(str2,2));

输出结果:7

substring()的两种用法

substring(int beginIndex)
返回该字符串的子字符串,子字符串从指定索引处的字符开始,直到该字符串的末尾结束。
例如

String str1="happyday";
System.out.println(str1.substring(2));

输出结果:"ppyday"
substring(int beginIndex, int endIndex)
返回该字符串的子字符串,子字符串从指定的索引beginIndex处开始,直到索引endIndex - 1处结束。因此子字符串的长度是endIndex-beginIndex。
例如

String str1="happyday";
System.out.println(str1.substring(2,6));

输出结果:"ppyd"


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM