如何从Java中仅提取辅音?

时间:2017-10-16 12:29:29

标签: java string

我有一个术语,例如String term =“Torx”,我想只提取辅音。所以输出将是“Trx”。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

使用字符串替换:

    String Str = "torx";

    Str = Str.replace("a","");
    System.out.println(Str);        
    Str = Str.replace("e","");
    System.out.println(Str);
    Str = Str.replace("i","");
    System.out.println(Str);
    Str = Str.replace("o","");
    System.out.println(Str);
    Str = Str.replace("u","");
    System.out.println(Str);

答案 1 :(得分:0)

您可以执行David Martin的操作,不做任何替换所有元音,或者换句话说,将它们移动:

String term = "Torx";

//Replacing 'a's
term = term.replaceAll("a", "").replaceAll("A", "");
//Replacing 'e's
term = term.replaceAll("e", "").repalceAll("E", "");
//Replacing 'i's
term = term.replaceAll("i", "").replaceAll("I", "");
//Replacing 'o's
term = term.replaceAll("o", "").replaceAll("O", "");
//Replacing 'u's
term = term.replaceAll("u", "").replaceAll("U", "");

System.out.println(term); //Without vowels

或者您可以搜索所有字母并仅保存辅音:

String consonantTerm = "";

char[] letters = term.toCharArray();
for (char letter : letters) {
    if (letter != 'a' && letter != 'A' &&
        letter != 'e' && letter != 'E' &&
        letter != 'i' && letter != 'I' &&
        letter != 'o' && letter != 'O" &&
        letter != 'u' && letter != 'u') {
         consonantTerm += letter;
     }
}

System.out.println(consonantTerm) //Without vowels
  

如果您希望新的String位于同一变量中。只需在for循环后添加term = consonantTerm;

答案 2 :(得分:-1)

您应该将<string>.charAt(index)方法与for循环一起使用,并简单地检查整个字符串。如果角色是辅音,只需将其连接到结果字符串上。