Java String substring()

substring() 方法用來擷取字串的一部分。

語法

// 從指定位置到結尾
string.substring(int beginIndex)

// 從指定位置到指定位置(不含 endIndex)
string.substring(int beginIndex, int endIndex)
  • beginIndex:起始位置(包含)
  • endIndex:結束位置(不包含)

範例

String s = "Hello World";

// 從索引 6 到結尾
String sub1 = s.substring(6);
System.out.println(sub1);  // "World"

// 從索引 0 到 5(不含 5)
String sub2 = s.substring(0, 5);
System.out.println(sub2);  // "Hello"

// 從索引 3 到 8
String sub3 = s.substring(3, 8);
System.out.println(sub3);  // "lo Wo"

索引說明

字串:  H  e  l  l  o     W  o  r  l  d
索引:  0  1  2  3  4  5  6  7  8  9  10
  • substring(6) 取得索引 6 到結尾
  • substring(0, 5) 取得索引 0, 1, 2, 3, 4(不含 5)

常見用法

取得檔案副檔名

String filename = "document.pdf";
int dotIndex = filename.lastIndexOf(".");
String extension = filename.substring(dotIndex + 1);
System.out.println(extension);  // "pdf"

取得檔名(不含副檔名)

String filename = "document.pdf";
int dotIndex = filename.lastIndexOf(".");
String name = filename.substring(0, dotIndex);
System.out.println(name);  // "document"

取得 URL 的網域

String url = "https://www.example.com/path";
int start = url.indexOf("://") + 3;
int end = url.indexOf("/", start);
String domain = url.substring(start, end);
System.out.println(domain);  // "www.example.com"

去掉前後幾個字元

String s = "[Hello]";

// 去掉第一個字元
String s1 = s.substring(1);
System.out.println(s1);  // "Hello]"

// 去掉最後一個字元
String s2 = s.substring(0, s.length() - 1);
System.out.println(s2);  // "[Hello"

// 去掉前後各一個字元
String s3 = s.substring(1, s.length() - 1);
System.out.println(s3);  // "Hello"

注意事項

索引超出範圍會拋出 StringIndexOutOfBoundsException

String s = "Hello";

// s.substring(10);      // 錯誤!
// s.substring(-1);      // 錯誤!
// s.substring(2, 10);   // 錯誤!
// s.substring(3, 1);    // 錯誤!beginIndex > endIndex

使用前最好先檢查:

String s = "Hello";
int start = 2;
int end = 4;

if (start >= 0 && end <= s.length() && start <= end) {
    String sub = s.substring(start, end);
    System.out.println(sub);
}