2010-05-06 4 views
0

je le code suivant en Java (qui fonctionnait très bien en C++ pour une raison quelconque) qui produit une erreur:Chaîne Java trop longue?

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

Sortie:

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: 

En utilisant une chaîne de longueur 200, cependant, la sortie suivante est produite:

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

C'est tout; aucune exception n'a été soulevée, juste ... rien. Que se passe-t-il ici?

Répondre

5

Le deuxième paramètre à String.substring est le dernier index pas la longueur de la sous-chaîne. Donc, vous voulez ce qui suit (je suppose):

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

Oui, c'était ça! Je vous remercie! Les choses sont un peu différentes de C++ :) – wrongusername

Questions connexes