如果端索引不超出界限,则返回string.length()的子字符串方法?

发布于 2025-01-26 06:14:37 字数 304 浏览 3 评论 0原文

基本上是标题。

String text = "abcdef";
String pattern = "defg";
int start = 3;
int end = 3 + pattern.length();
System.out.println(text.substring(start,end));

现在,这会从界限中引出索引,但是有些API可以解决此问题。 现在我只是在做

if (end > text.length()){
end = text.length();
}

Basically the title.

String text = "abcdef";
String pattern = "defg";
int start = 3;
int end = 3 + pattern.length();
System.out.println(text.substring(start,end));

Now that throws index out of bounds error but is there some API that can work around this.
Right now I'm just doing

if (end > text.length()){
end = text.length();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

羁客 2025-02-02 06:14:37

类似的方法,但使用Math.min以较短的方式处理它:

text.substring(start, Math.min(end, text.length()));

Similar approach but with Math.min to tackle it in a shorter way:

text.substring(start, Math.min(end, text.length()));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文