Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
Example 1:
Input: "leetcodeisacommunityforcoders" Output: "ltcdscmmntyfrcdrs"
Example 2:
Input: "aeiou" Output: ""
Note:
Sconsists of lowercase English letters only.1 <= S.length <= 1000
Approach #1 我的解法,new StringBuilder()
public class Solution {
public String removeVowels(String S) {
StringBuilder sb = new StringBuilder();
for(int i=0;i<S.length();i++){
if(S.charAt(i)-'a'!=0 && S.charAt(i)-'e'!=0&&S.charAt(i)-'i'!=0&&S.charAt(i)-'o'!=0&&S.charAt(i)-'u'!=0)
sb.append(S.charAt(i));
}
return sb.toString();
}
}
Approach #2 string.replaceAll()
public String removeVowels(String S) {
return S.replaceAll("[a,e,i,o,u]", "");
}
学习 string.replaceAll()
replaceAll() 方法使用给定的参数 replacement 替换字符串所有匹配给定的正则表达式的子字符串。
语法
public String replaceAll(String regex, String replacement)
参数
-
regex -- 匹配此字符串的正则表达式。
-
newChar -- 用来替换每个匹配项的字符串。
返回值
成功则返回替换的字符串,失败则返回原始字符串。

本文介绍了一种从给定字符串中移除元音字母('a', 'e', 'i', 'o', 'u')的方法,并提供了两种实现方案:一种是使用StringBuilder逐字符构建新字符串;另一种是利用String的replaceAll方法通过正则表达式一次完成替换。
6万+

被折叠的 条评论
为什么被折叠?



