英文:
Java- Remove vowels from user input using nested for loop
问题
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
char[] vowels = {'a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U'}; // 字符数组
Scanner in = new Scanner(System.in);
System.out.println("输入短语:");
String phrase = in.nextLine();
for (int i = 0; i < phrase.length(); i++) {
for (int j = 0; j < vowels.length; j++) {
char ch = vowels[j];
char ch2 = phrase.charAt(i);
if (ch == ch2) {
phrase = phrase.replace(phrase.charAt(i), ' ');
}
}
}
System.out.println(phrase);
}
}
英文:
So I've seen this simple question and answer a few times and I just wanted to try a different way to solve it.
My solution does work- it replaces every vowel with an empty char.
However, I've been trying to figure out a way in my code where the char can be simply removed and not replaced with empty char ' '.
For example...
In my code, if the user inputted: happy, the result is h ppy
Although this does answer the question, I would like to also see the output: hppy
Hopefully, I can get some help, thanks!
import java.util.Scanner;
public class Main {
public static void main(String args[]){
char [] vowels = {'a','e','i','o','u',
'A','E','I','O','U'};//char array
Scanner in = new Scanner(System.in);
System.out.println("Enter phrase: ");
String phrase = in.nextLine();
for (int i = 0; i < phrase.length(); i++) {
for (int j = 0; j < vowels.length; j++) {
char ch = vowels[j];
char ch2 = phrase.charAt(i);
if (ch == ch2) {
phrase = phrase.replace(phrase.charAt(i), ' ');
}
}
}
System.out.println(phrase);
</details>
# 答案1
**得分**: 2
这应该可以运行:`phrase.replaceAll("[aeiouAEIOU]", "")`
<details>
<summary>英文:</summary>
This ought to work: `phrase.replaceAll("[aeiouAEIOU]", "")`
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论