2014-10-08 27 views
-2

我想分開一個長字符串到每個字,並按順序打印它們在Java中,但它會拋出異常StringIndexOutOfBounds。繼承人的代碼,任何輸入的高度讚賞:屠宰一個字符串明智

public class SpellingChecker { 
public static void test(String str) { 
    int i=0,j=0,n=str.length(); 
    String temp=""; 
    do{ 
     for(i=j;str.charAt(i)!=' ';i++) 
      temp+=str.charAt(i); 
     temp+='\0'; 
     System.out.println(temp); 
     temp=""; 
     j=i+1; 
    }while(j<n); 
} 
public static void main(String[] args) { 
    java.util.Scanner input = new java.util.Scanner(System.in); 
    System.out.print("Enter string for which you want to check spelling : "); 
    String strng=input.next(); 
    test(strng); 
    } 
} 
+0

請問你能解釋一下嗎?在測試功能? – 2014-10-08 19:37:54

+0

這段代碼正在做一些與預期不同的事 – 2014-10-08 19:43:01

回答

2

您正在使用next()而不是nextLine()來掃描您的句子。所以,你會只獲得第一個字,而不是所有的話..

所以將其更改爲

String strng = input.nextLine(); 

下一頁您test()方法,這應該是模板

public static void test(String str) { 
    String[] words = str.split("\\s+"); 
    for(String word: words) { 
     System.out.println(word); 
     //Here decide what you want to do with each word 
    } 
} 
+0

感謝您指出一個。你的代碼是絕對沒問題的,但是我在設置整個字符串之前增加了一個空格來保持我的「穴居人」版本,即 'str + ='';'在循環中進行編輯之前。 – TweaknFreak 2014-10-08 19:52:34

2

這會做你想要什麼:

String[] words = str.split("\\s+"); 
StringBuilder temp = new StringBuilder(); 
for (String word : words) 
    temp.append(word).append("\0"); 
+0

最好不要在循環內使用'+ ='字符串:它變成了'O(n2)'操作。 – StriplingWarrior 2014-10-08 19:47:30

+0

謝謝,我會記住這一點。這是版本0.1,所以我甚至沒有考慮複雜情況。將來一定會保重的。 – TweaknFreak 2014-10-08 19:51:03

+0

@StriplingWarrior謝謝,我改變它使用'StringBuilder' – msrd0 2014-10-08 20:22:05

2

如果我理解你的問題,你可以重寫test(String)使用String.split(String)喜歡的東西,

public static void test(String str) { 
    String[] words = str.split("\\s+"); 
    for (String word : words) { 
     System.out.println(word); 
    } 
} 
1
for(i=j;str.charAt(i)!=' ';i++) 
temp+=str.charAt(i); 

我認爲這超出了範圍,如果字符串沒有任何空間