2015-03-08 40 views
-2

这里是我的代码,我用空白空间代替元音:为什么在用空白空间替换元音后没有改变句子?

System.out.println("Enter a sentence"); 
String sentence=in.nextLine(); 
for(int i=0;i<sentence.length();i++) { 
    if(sentence.charAt(i)=='a'||sentence.charAt(i)=='e'|| sentence.charAt(i)=='i'|| 
     sentence.charAt(i)=='o'|| sentence.charAt(i)=='u') 
    { 
     sentence.replace(sentence.charAt(i), ' '); 
    } 
} 
System.out.println(sentence); 
+2

你试过'句子= sentence.replace(sentence.charAt(我),'“);' – 2015-03-08 19:31:15

+0

现在我有。感谢您的更正现在它工作 – ema 2015-03-08 19:33:15

+0

关闭作为重复更好的候选人:[提示java.lang.String.replace问题?](http://stackoverflow.com/q/1166905/217324) – 2015-07-15 19:10:11

回答

0

你有replace()

public static void main(String[] args) throws Exception { 
    Scanner in = new Scanner(System.in); 

    System.out.println("Enter a sentence"); 
    String sentence = in.nextLine(); 
    for (int i = 0; i < sentence.length(); i++) { 
     if (sentence.charAt(i) == 'a' || sentence.charAt(i) == 'e' || sentence.charAt(i) == 'i' 
       || sentence.charAt(i) == 'o' || sentence.charAt(i) == 'u') { 
      // Assign the results of replace() back to sentence 
      sentence = sentence.replace(sentence.charAt(i), ' '); 
     } 
    } 
    System.out.println(sentence); 
} 

您能抽出自己for环和长篇大论ifreplaceAll()后重新分配句子使用图案

"[aAeEiIoOuU]"

public static void main(String[] args) throws Exception { 
    Scanner in = new Scanner(System.in); 

    System.out.println("Enter a sentence"); 
    String sentence = in.nextLine(); 

    // Replace all english upper-case & lower-case vowels 
    System.out.println(sentence.replaceAll("[aAeEiIoOuU]", " ")); 
} 

结果:

Enter a sentence 
thE Quick Brown FOX 
th Q ck Br wn F X