2012-08-04 38 views
1
public class ReplaceVowels { 

    public static void main(String args[]) throws IOException { 
     BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); 
     System.out.println("Enter the String:"); 
     String str = bf.readLine(); 

     char[] c = new char[str.length()]; 
     for (int i = 0; i < str.length(); i++) { 

      if (c[i] == 'a' || c[i] == 'e' || c[i] == 'i' || c[i] == 'o' 
        || c[i] == 'u') { 

       System.out.println(str.replace(c[i], '?')); 

      } 

     } 

    } 
} 

爲什麼str.replace方法不起作用?我應該怎麼做才能使它工作?如何用Java中的特殊字符替換元音?

回答

8

在你的代碼中,你正在創建一個新的字符數組,它與你的字符串的長度相同,但是你沒有用任何值初始化數組。

相反,嘗試:

char[] c = str.toCharArray(); 

然而,這不是做你正在試圖做的最好的方式。你並不需要一個字符數組或一個if語句來替換字符串中的字符:

String str = bf.readLine(); 
str.replace('a', '?'); 
str.replace('e', '?'); 
str.replace('i', '?'); 
str.replace('o', '?'); 
str.replace('u', '?'); 
System.out.println(str); 

replace功能將取代它找到任何(和所有)字符,或者它會做什麼,如果這個角色沒有按」 t存在於字符串中。

您可能還需要考慮使用regular expressions(如edwga的答案指出),這樣就可以縮短這5函數調用到一個:

str.replaceAll("[aeiou]", "?"); 
+0

謝謝你們欣賞它 – keith 2012-11-05 20:24:12

+0

字符串是不可改變的,'str.replace'不會修改原始的字符串,它將返回新/獨立的一個修改後的內容。你可能意思是'str = str.replace(...)'。 – Pshemo 2017-11-29 17:36:05

5

老實說,這個解決方案是比較不切實際的。您應該使用str.replaceAll()方法。

(read in the String str); 
str = str.replaceAll("[aeiou]", "?"); 
System.out.println(str); 

這樣做是它使用正則表達式「[aeiou]同時」,並以特殊字符替換它(「?」)。正則表達式是一個複雜的主題,但是它只是檢測元音的每個實例。 你可以閱讀更多關於正則表達式在http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html

+4

你也可以在正則表達式中添加'(?i)',使它不區分大小寫*就像'「(?i)[aeiou]」' – Pshemo 2012-08-04 17:16:21

0

以上所有答案的作品。 只是增加了一些區分大小寫捕捉大寫元音(使用掃描器類)

 String str1, str2; 
     Scanner scan = new Scanner(System.in); 

     System.out.print("Enter a String : "); 
     str1 = scan.nextLine(); 
     str2 = str1.replaceAll("[aeiouAEIOU]", "?"); 
     // adding AEIOU to capture Vowels in uppercase. 
     System.out.println("All Vowels Removed Successfully"); 

     System.out.println(str2);