// 示例代码:Java 截取字符串方法
public class StringSubstringExample {
public static void main(String[] args) {
String str = "Hello, World!";
// 使用 substring 方法截取字符串
// substring(int beginIndex):从指定索引开始到字符串末尾
String result1 = str.substring(7);
System.out.println("substring(7): " + result1); // 输出: World!
// substring(int beginIndex, int endIndex):从指定索引开始到结束索引(不包括结束索引)
String result2 = str.substring(0, 5);
System.out.println("substring(0, 5): " + result2); // 输出: Hello
// 注意:如果 beginIndex 大于 endIndex 或者超出字符串长度,会抛出 StringIndexOutOfBoundsException 异常
}
}
substring(int beginIndex)
:从指定的起始索引 beginIndex
开始,一直到字符串的末尾,返回一个新的字符串。substring(int beginIndex, int endIndex)
:从指定的起始索引 beginIndex
开始,一直到指定的结束索引 endIndex
(不包括 endIndex
),返回一个新的字符串。beginIndex
大于 endIndex
,则会抛出 StringIndexOutOfBoundsException
异常。上一篇:java 字符串截取
下一篇:java threadlocal
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站