簡體   English   中英

Java字符串太長?

[英]Java string too long?

我有以下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: 

這就對了; 沒有提出任何例外,只是……什么都沒有。 這是怎么回事

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM