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:
S
consists 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 -- 用来替换每个匹配项的字符串。
返回值
成功则返回替换的字符串,失败则返回原始字符串。