我應該輸入一個字符串,並與&
,2
,U
和4
更換所有and
,to
,you
和for
子。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
這似乎切斷了返回的字符串的第一個空間
後,我不知道是怎麼回事,爲什麼它不工作,因爲它應該。 我在做什麼錯?
「爲什麼它不工作,因爲它應該。」它應該輸出什麼? – manouti
將字符串寫在紙上。手動取代一切。你會看到..'replaceAll'用第二個參數中的文本替換第一個參數中的所有文本。有關信息,請閱讀http://docs.oracle.com/javase/7/docs/api/java/lang/String.html。 –
您應該注意,您正在向該方法傳遞一個參數,但用另一個String在該方法內覆蓋它。也許這會導致你的困惑。 – Eran