英文:
Java replace a character in a string
问题
public Boolean isVowel(char ch){
char ch2 = Character.toLowerCase(ch);
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for(int i = 0; i < vowels.length; i++){
if (ch2 == vowels[i]) {
return true;
}
}
return false;
}
public String replaceVowels(String phrase, char ch){
String newP = "";
for(int i = 0; i < phrase.length(); i++){
char c = phrase.charAt(i);
Boolean vowel = isVowel(c);
if(vowel){
newP = phrase.replace(c, ch);
}
}
return newP;
}
英文:
I am writing a method to replace all vowels in a string with a given character, but it does not work for strings with more than one vowel. It works for "heel" but not for "hello". Please help. My code below:
public Boolean isVowel(char ch){
char ch2 = Character.toLowerCase(ch);
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for(int i = 0; i < vowels.length; i++){
if (ch2 == vowels[i]) {
return true;
}
}
return false;
}
public String replaceVowels(String phrase, char ch){
String newP = "";
for(int i = 0; i < phrase.length(); i++){
char c = phrase.charAt(i);
Boolean vowel = isVowel(c);
if(vowel){
newP = phrase.replace(c, ch);
}
}
return newP;
}
答案1
得分: 6
public String replaceVowels(final String phrase, final String ch) {
return phrase.replaceAll("[aeiou]", ch);
}
英文:
public String replaceVowels(final String phrase,final String ch) {
return phrase.replaceAll("[aeiou]", ch);
}
答案2
得分: 2
这是一种用 Java 字符替换字符串中所有元音字母的方法。其中的 (?i) 表示不区分大小写。"" +ch 从字符中获取一个字符串。
String str = "hEllo";
char ch = 'X';
str = str.replaceAll( "(?i)[aeiou]", "" +ch );
也可以更明确地区分大小写,如下:
String str = "hEllo";
char ch = 'X';
str = str.replaceAll( "[aeiouAEIOU]", "" +ch );
英文:
Here is one way to replace all vowels in a string with an java char. The (?i) is to make it case insensitive. The "" +ch gets a string from the char.
String str = "hEllo";
char ch = 'X';
str = str.replaceAll( "(?i)[aeiou]", "" +ch );
Could also be more explicit with case like:
String str = "hEllo";
char ch = 'X';
str = str.replaceAll( "[aeiouAEIOU]", "" +ch );
答案3
得分: 1
你的问题在于 newP = phrase.replace(c, ch);
你正在赋予一个最终值。
String newP = phrase;
for(int i = 0; i < phrase.length(); i++){
char c = phrase.charAt(i);
Boolean vowel = isVowel(c);
if(vowel){
newP = newP.replace(c, ch);
}
}
根据Alex的回答,更好的解决方案是添加 String:
phrase.replaceAll("[aeiou]", "" + ch);
英文:
Your problem is newP = phrase.replace(c, ch);
You are assigning a last value.
String newP = phrase;
for(int i = 0; i < phrase.length(); i++){
char c = phrase.charAt(i);
Boolean vowel = isVowel(c);
if(vowel){
newP = newP.replace(c, ch);
}
}
Better solution as answered by Alex just add String,
phrase.replaceAll("[aeiou]", ""+ch);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论