2015-11-12 27 views
2

我應該輸入一個字符串,並與&2U4更換所有andtoyoufor子。Java的替代()問題

當我輸入字符串"and , and,and , to , to,to , you ,you , you, for ,for , for,a , a,e , e,i , i,o , o,u , u"時,它只在打印時輸出and

public void simplify() 
{ 
    System.out.println("Enter a string to simplify: "); 
    String rope = in.next(); 
    System.out.println(simplifier(rope)); 
} 
public String simplifier(String rope) 
{ 

    rope = rope.replace(" and "," & "); 
    rope = rope.replace(" and"," &"); 
    rope = rope.replace("and ","& "); 
    rope = rope.replace(" to "," 2 "); 
    rope = rope.replace(" to"," 2"); 
    rope = rope.replace("to ","2 "); 
    rope = rope.replace(" you "," U "); 
    rope = rope.replace("you ","U "); 
    rope = rope.replace(" you"," U"); 
    rope = rope.replace(" for "," 4 "); 
    rope = rope.replace("for ","4 "); 
    rope = rope.replace(" for"," 4"); 
    rope = rope.replace("a ",""); 
    rope = rope.replace(" a",""); 
    rope = rope.replace("e ",""); 
    rope = rope.replace(" e",""); 
    rope = rope.replace("i ",""); 
    rope = rope.replace(" i",""); 
    rope = rope.replace(" o",""); 
    rope = rope.replace("o ",""); 
    rope = rope.replace("u ",""); 
    rope = rope.replace(" u",""); 
    System.out.print(rope); 
    return rope; 
} 

輸出:and and

這似乎切斷了返回的字符串的第一個空間

後,我不知道是怎麼回事,爲什麼它不工作,因爲它應該。 我在做什麼錯?

+2

「爲什麼它不工作,因爲它應該。」它應該輸出什麼? – manouti

+0

將字符串寫在紙上。手動取代一切。你會看到..'replaceAll'用第二個參數中的文本替換第一個參數中的所有文本。有關信息,請閱讀http://docs.oracle.com/javase/7/docs/api/java/lang/String.html。 –

+0

您應該注意,您正在向該方法傳遞一個參數,但用另一個String在該方法內覆蓋它。也許這會導致你的困惑。 – Eran

回答

1

這是我如何簡化你的代碼,並得到正確的結果:

String rope = "and , and,and , to , to,to , you ,you , you, for ,for , for,a , a,e , e,i , i,o , o,u , u"; 

    // rope = rope.replaceAll(" ", ""); 
    rope = rope.replaceAll("and", "&"); 
    rope = rope.replaceAll("to", "2"); 
    rope = rope.replaceAll("you", "U"); 
    rope = rope.replaceAll("for", "4"); 
    rope = rope.replaceAll("a", ""); 
    rope = rope.replaceAll("e", ""); 
    rope = rope.replaceAll("i", ""); 
    rope = rope.replaceAll("o", ""); 
    rope = rope.replaceAll("u", ""); 
    System.out.println(rope); 
+0

謝謝你你的幫助,這對我有用。謝謝:) – James

+0

@James很高興它幫助:)請選擇我的答案或投票,所以我可以更好地工作,以幫助他人 – Arash

0

更換第一rope = rope.replace(" and "," & ");rope = rope.replace("and "," & ");

現在,它應該工作。問題在於,第一個「和」你試圖替換的是and,而不是and,這就是爲什麼剩下並且沒有被替換。

還刪除simplifier的第二行,即System.out.print(rope);。這是重複的,因爲您已在調用方法中打印結果。


更新: 我看到你正試圖在這裏做。試試這個:

對於每個要替換的單詞,只需替換一次即可。所以對於and,做到:

rope.replace("and", "&"); 

對於to,做到:

rope.replace("to", "2"); 

不要添加單詞之間的任何空間,這是沒有必要的。做replace()曾經將取代所有這個詞的發生。

+0

它似乎不工作,當我輸入'和asdfasdf',它仍然輸出和和' – James

+0

我試過你的建議,但它仍然沒有工作。看起來當返回方法在字符串中遇到空格時停止,因爲當我輸入'和你好',它返回'&',並且當我輸入'和你好','和'返回 – James