Java字符串太长了?

时间:2010-05-06 04:08:07

标签: java string

我在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: 

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

1 个答案:

答案 0 :(得分: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...
}