public class StringSubstringExample {
public static void main(String[] args) {
// 定义一个字符串
String str = "Hello, Java World!";
// 使用 substring 方法截取字符串的一部分
// substring(int beginIndex):从指定索引开始,到字符串结束
String result1 = str.substring(7); // 截取从索引7开始到结尾的子串
System.out.println("result1: " + result1); // 输出: Java World!
// substring(int beginIndex, int endIndex):从指定索引开始,到指定索引结束(不包括结束索引)
String result2 = str.substring(0, 5); // 截取从索引0开始到索引5(不包括)的子串
System.out.println("result2: " + result2); // 输出: Hello
// 注意:如果索引超出范围,会抛出 StringIndexOutOfBoundsException 异常
}
}
substring(int beginIndex):该方法从指定的起始索引 beginIndex 开始,截取到字符串的末尾。substring(int beginIndex, int endIndex):该方法从指定的起始索引 beginIndex 开始,截取到指定的结束索引 endIndex(不包括 endIndex)。通过这两个方法可以方便地从字符串中提取所需的子串。
上一篇:java中byte类型取值范围
下一篇:java时间戳转换
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站