简体   繁体   English

Java字符串太长?

[英]Java string too long?

I have the following code in Java (which worked just fine in C++ for some reason) which produces an error: 我有以下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...
}

Output: 输出:

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: 

Using a string of length 200, however, the following output is produced: 但是,使用长度为200的字符串,将产生以下输出:

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

That is it; 这就对了; no exceptions raised, just... nothing. 没有提出任何例外,只是……什么都没有。 What is happening here? 这是怎么回事

The second parameter to String.substring is the last index not the length of the substring. String.substring的第二个参数是最后一个索引,而不是子字符串的长度。 So you want the following (I assume): 因此,您需要以下内容(我假设):

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...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM