用字符串替换辅音

时间:2015-02-16 02:56:23

标签: java string replace

我在写下此功能的代码时遇到了麻烦。

更换辅音

/** Return a string that is s but with all lowercase consonants (letters of
 * the English alphabet other than the vowels a, e, i, o, u) replaced with
 * _, and all uppercase consonants replaced with ^.
 *
 * Examples: For s = "Minecraft" return "^i_e__a__".
 *           For s = "Alan Turing" return "A_a_ ^u_i__".

这是我到目前为止所做的:

String consonants = "bcdfghjklmnpqrstvwxyz";
for(int j = 0; j < consonants.length(); j++ ){
    int start = 0;
    if s.charAt(start) == consonants( I am unsure to tell it to look through the string I made)
        s.charAt(start).replace(s.substring(start,1), ("_"));
        if s.charAt(start) == s.substring(start,start+1).ToUpperCase(){
            s.charAt(start) = "'";
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您可以使用基于负前瞻的正则表达式,或者您需要手动编写所有辅音。

String s = "Minecraft";
String m = s.replaceAll("(?![aeiouAEIOU])[a-z]", "_").replaceAll("(?![aeiouAEIOU])[A-Z]", "^");
System.out.println(m);

输出:

^i_e__a__

答案 1 :(得分:-2)

String myName = "domanokz";
myName.charAt(4) = 'x';

如果那不是你要找的东西:

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

或者您可以使用StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);