2014-02-27 29 views
-3

我想存儲所有可能的子串在String []。我試過這個,但得到一個錯誤:存放在字符串中所有可能的子[]

public void sub(String word){                       
    String [] Str=new String[100];                    
    int n=0;                                 
    for (int from = 0; from < word.length(); from++) {         
     for (int to = from + 1; to <= word.length(); to++) {    
      str[n]=word.substring(from, to);    
      n++;    
      System.out.println(str[n]);   
     }    
    }   
}    

什麼是解決方案?

+4

有什麼錯誤? – PakkuDon

+0

當你輸入你的問題時,它旁邊有一個橙色的方框,標題爲「如何格式化**」。值得一讀。頂部還有一個工具欄,用於製作格式,標記代碼等等,方便,並在下方顯示預覽區域,以準確顯示您的問題在發佈時的樣子。對於你的下一個問題,請使用這些工具。 (另外,縮進你的代碼。)這次我爲你糾正了一些事情。 –

+0

好吧,我明白了。錯誤是:無法找到符號,變量str,loction:class substring – user3359479

回答

3

error is: cannot find symbol, variable str, loction: class substring

那麼,這相當清楚地告訴你錯誤是什麼:你還沒有申報str。您宣佈Str,但Java的標識是區分大小寫的,strStr是不一樣的標識符。

因此改變

String [] Str=new String[100]; 

String [] str=new String[100]; 
//  ^--- lower case 

之前,當你沒有說是什麼錯誤,有一對夫婦的其他東西Pshemo和我(還有其他)注意到:

您有一個順序的問題在這裏:

str[n]=word.substring(from, to);    
n++;    
System.out.println(str[n]); 

...因爲輸出字符串之前,你遞增n,你總是會輸出null。只需動增量修復:

str[n]=word.substring(from, to);    
System.out.println(str[n]); 
n++;    

可能會出現更長的話,其中的子串數可以多於100應避免創建固定大小的數組的情況下,但儘量使用動態大小集合另一個可能的問題像List

List<String> str = new ArrayList<String>(); 

放或讀到這裏的元素只需使用str.add(substring)str.get(index)

+0

tnx。但它只是打印一個,al,l。 – user3359479

+0

@Pshemo現在它工作正常。全部都是。 – user3359479

+0

現在我有String [] wordsArray,我想查找單詞數組Array [i]是子串換句話說數組。任何解決方案 – user3359479

相關問題