2010-05-06 123 views
0

我有在Java中下面的代码(其工作用C就好++出于某种原因),它产生一个错误:Java字符串太长了?

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: 

就是这样;没有例外提出,只是......没有。这里发生了什么?

回答

5

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

是的,就是这样!谢谢!事情与C++有点不同:) – wrongusername 2010-05-06 04:16:41