简体   繁体   中英

Java string too long?

I have the following code in Java (which worked just fine in C++ for some reason) which produces an error:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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