我想删除数组中每个单词的所有元音。所以我想出了这个:
public class AnotherExercise {
public static void main (String[] args){
String[] intruments = {"cello", "guitar", "violin", "double bass"}; //the array of words
String[] vowels = {"a", "e", "i", "o", "u"}; // the array of vowels
String[] intruments2 = new String[5]; //the array of wrods without vowels
String nothing = ""; // used to replace a vowel to nothing
for (int i = 0; i < 4; i++){ // first for loop to go through all of the intruments
for(int e = 0; e < 5; e++){ //second for loop to go through all the vowels
intruments2[i] = intruments[i].replaceAll(vowels[e], nothing); //replacing vowels
//and storing them in a new array
}
System.out.println(intruments2[i]); //outputting the words without vowels
}
}
}
从我尝试的所有选项中,我猜这一个是最好的,但我仍然无法使它工作,它输出:
cello
gitar
violin
doble bass
我认为最奇怪的部分是它确实取代了“你”。这可能是一个愚蠢的错误,但我无法弄明白。
答案 0 :(得分:0)
方法字符串。ReplaceAll接收正则表达式作为第一个参数。它允许您一次性删除所有元音:
public class AnotherExercise {
public static void main (String[] args){
String[] intruments = {"cello", "guitar", "violin", "double bass"};
String[] intruments2 = new String[5];
String nothing = "";
for (int i = 0; i < 4; i++){
intruments2[i] = intruments[i].replaceAll("a|e|i|o|u", nothing);
System.out.println(intruments2[i]);
}
}
}
而且,是的,关于您的版本的问题。在内部循环中,您始终将替换应用于字符串的初始版本。所以你只能从最后一次尝试得到结果 - 字母'你'。