我正在尝试编写将字符串中的所有元音加倍的代码.所以如果字符串是hello,它将返回heelloo.这就是我目前拥有的:
public String doubleVowel(String str)
{
for(int i = 0; i <= str.length() - 1; i++)
{
char vowel = str.charAt(i);
if(vowel == 'a' || vowel == 'e' || vowel == 'i' || vowel == 'o' || vowel == 'u')
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ell*_*sch 13
您可以使用单个调用的正则表达式,String.replaceAll(String, String)您的方法可能是static因为您不需要任何实例状态(另外,不要忘记大写元音).就像是
public static String doubleVowel(String str) {
return str.replaceAll("([AaEeIiOoUu])", "$1$1");
}
Run Code Online (Sandbox Code Playgroud)
当$1比赛分组中表达的第一个(只)模式().
您需要创建一个临时额外字符串(构建器)并将元音两次添加到该局部变量,然后返回它:
public String doubleVowel(String str)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i <= str.length() - 1; i++)
{
char vowel = str.charAt(i);
if(vowel == 'a' || vowel == 'e' || vowel == 'i' || vowel == 'o' || vowel == 'u')
{
sb.append(vowel); // add it to the string
}
sb.append(vowel); // add any character always, vowels have been added already, resulting in double vowels
}
return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4188 次 |
| 最近记录: |