您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,可以使用substring()
方法来实现字符串的截取。substring()
方法有两种重载形式:
substring(beginIndex)
: 从给定的开始索引(包括)截取字符串,直到字符串的末尾。substring(beginIndex, endIndex)
: 从给定的开始索引(包括)截取字符串,直到指定的结束索引(不包括)。以下是一些示例:
public class SubstringExample {
public static void main(String[] args) {
String str = "Hello, World!";
// 截取从索引0开始到索引5(不包括)的子字符串
String sub1 = str.substring(0, 5);
System.out.println(sub1); // 输出 "Hello"
// 截取从索引7开始到字符串末尾的子字符串
String sub2 = str.substring(7);
System.out.println(sub2); // 输出 "World!"
}
}
请注意,substring()
方法的参数索引是从0开始的。如果提供的索引超出字符串的范围,将抛出StringIndexOutOfBoundsException
异常。因此,在使用substring()
方法时,请确保提供的索引在有效范围内。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。