一、基本概念
Java中的substring()方法可用於提取字元串中的一部分。它需要一個起始索引和一個結束索引作為參數,返回以這兩個索引為範圍的字元串。下面是幾個重要的概念:
1、起始索引必須大於等於0,小於字元串長度。
2、結束索引必須大於起始索引,小於等於字元串長度。
3、返回的字元串包括起始索引處的字元但不包括結束索引處的字元。
二、簡單用法
以下代碼演示了如何在Java中使用substring()方法:
String str = "Hello World!"; String subStr = str.substring(6, 11); System.out.println(subStr); // 輸出World
三、提取前綴或後綴
使用substring()方法可以輕鬆地從字元串中提取前綴或後綴。比如獲取一個文件的後綴名,只需找到最後一個”.”的位置,然後使用substring()方法提取即可:
String fileName = "example.txt"; int dotIndex = fileName.lastIndexOf("."); String extension = fileName.substring(dotIndex + 1); System.out.println(extension); // 輸出txt
同樣的,獲取文件名也很簡單,只需使用substring()方法獲取”.”之前的部分:
String fileName = "example.txt"; int dotIndex = fileName.lastIndexOf("."); String name = fileName.substring(0, dotIndex); System.out.println(name); // 輸出example
四、處理字元串中的空格
使用trim()方法可以去除字元串兩端的空格。但有時我們需要去除中間的空格,此時可以結合使用replaceAll()和substring()方法:
String str = " This is a test. "; str = str.replaceAll("\\s+", " "); String subStr = str.substring(0, 16); // 去除後的長度為16 System.out.println(subStr); // 輸出This is a test.
五、處理漢字
對於包含中文的字元串,使用substring()方法需要注意漢字的字元編碼問題。例如下面的代碼:
String str = "中華人民共和國"; String subStr = str.substring(2, 4); System.out.println(subStr); // 輸出��
可以看到,輸出為亂碼。這是因為中文字元在Java中是雙位元組字元,substring()方法對於中文的截取需要手動計算位元組長度:
String str = "中華人民共和國"; String subStr = str.substring(4, 8); System.out.println(subStr); // 輸出人民共和國
六、其他用法
除了以上常見的用法外,substring()方法還可以用於將字元串轉化為數字進行計算,例如:
String str = "123456"; int sum = 0; for (int i = 0; i < str.length(); i++) { sum += Integer.parseInt(str.substring(i, i + 1)); } System.out.println(sum); // 輸出21
以上代碼將字元串”123456″中的每個數字取出並轉化為整型進行求和。
總的來說,Java中的substring()方法是處理字元串時非常常用的方法之一,掌握使用技巧和注意事項可以讓我們的字元串操作更加高效、靈活。
原創文章,作者:TDAOC,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/313414.html