gpt4 book ai didi

Java字符串太长?

转载 作者:行者123 更新时间:2023-12-01 17:39:29 25 4
gpt4 key购买 nike

我在 Java 中有以下代码(由于某种原因在 C++ 中运行得很好),它会产生错误:

int a;
System.out.println("String length: " + input.length());
for(a = 0; ((a + 1) * 97) < input.length(); a++) {
System.out.print("Substring at " + a + ": ");
System.out.println(input.substring(a * 97, 97));
//other code here...
}

输出:

String length: 340
Substring at 0: HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHe
Substring at 1:
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: -97
//long list of "at ..." stuff
Substring at 2:

但是,使用长度为 200 的字符串,会产生以下输出:

String length: 200
Substring at 0: HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHe
Substring at 1:

就是这样;没有提出任何异常(exception),只是……什么都没有。这里发生了什么?

最佳答案

第二个参数为String.substring最后一个索引而不是子字符串的长度。所以你想要以下内容(我假设):

int a;
System.out.println("String length: " + input.length());
for(a = 0; ((a + 1) * 97) < input.length(); a++) {
System.out.print("Substring at " + a + ": ");
System.out.println(input.substring(a * 97, (a + 1) * 97));
//other code here...
}

关于Java字符串太长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2778381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com