了解Java中的substring()函数实现字符串截取
发布时间:2023-07-25 18:59:53
substring()函数是Java中的一个字符串截取方法,用于从一个字符串中获取子字符串。
它有两种重载形式:
1. public String substring(int startIndex):返回从startIndex位置开始到原字符串末尾的子字符串。
2. public String substring(int startIndex, int endIndex):返回从startIndex位置开始到endIndex位置的子字符串,包含startIndex位置的字符但不包含endIndex位置的字符。
下面是一些使用substring()函数的示例:
示例1:
String str = "Hello World"; String sub = str.substring(6); System.out.println(sub); // 输出:World
示例2:
String str = "Hello World"; String sub = str.substring(0, 5); System.out.println(sub); // 输出:Hello
注意:
- 字符串中的索引是从0开始的,startIndex和endIndex都是基于0的索引。
- 如果startIndex大于等于字符串的长度,将会抛出一个StringIndexOutOfBoundsException。
- 如果endIndex大于字符串的长度,substring()方法会自动将endIndex重置为字符串的长度。
- 如果startIndex大于endIndex,将会返回一个空字符串。
substring()函数是一个非常常用的字符串操作方法,在实际开发中经常用于截取字符串的一部分,例如从URL中截取域名、从文件路径中截取文件名等等。
