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