例如,当我们指定要删除的字符为Battle of the Vowels:Hawaii vs Gronzy
时,给定一个aeiou
字符串,该函数应将字符串转换为Bttl f th V wls:Hw vs Grzny
。
在Programming Interviews Exposed一书中找到了这个问题。这在C中有解释,但我对Java感兴趣。
答案 0 :(得分:22)
一种简单的方法是使用正则表达式:
"Battle of the Vowels:Hawaii vs Gronzy".replaceAll("[aeiou]","")
一些Java类库API文档:
String.replaceAll:http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)
模式和正则表达式:http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html#sum
答案 1 :(得分:1)
public class RemoveChars {
char[] replaceChar = {'a','e','i','o','u'};
public static void main(String[] args) {
String src = "Battle of the Vowels:Hawaii vs Gronzy";
System.out.println(new RemoveChars().removeChar(src));
}
public String removeChar(String src){
char[] srcArr = src.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < srcArr.length; i++) {
char foundChar = isFound(srcArr[i]);
if(foundChar!='\0')
sb.append(foundChar);
}
return sb.toString();
}
public char isFound(char src){
for (int i = 0; i < replaceChar.length; i++) {
if(src==replaceChar[i]){
return '\0';
}
}
return src;
}
}
答案 2 :(得分:0)
public class RemoveCharacters
{
static String removeCharsFromString(String word1, String word2)
{
StringBuilder sb = new StringBuilder(word1);
System.out.println(sb);
//char[] word2characters= word2.toCharArray();
HashMap<Character, Integer> table = new HashMap<Character, Integer>();
for (int i = 0; i < word2.length(); i++)
{
table.put(word2.charAt(i), 1);
}
int p = 0;
for (int i = 0; i < word1.length(); i++)
{
if (table.containsKey(word1.charAt(i)))
{
if (p == 0)
{
sb.deleteCharAt(i);
//p++;
}
else
{
sb.deleteCharAt(i - p);
}
//System.out.println(sb);
p++;
}
}
return sb.toString();
}
public static void main(String[] args)
{
System.out.println("Enter your string");
Scanner sc = new Scanner(System.in);
String originalword = sc.nextLine();
System.out.println("Enter the remove string");
Scanner sc1 = new Scanner(System.in);
String removecharacters = sc1.nextLine();
String result = removeCharsFromString(originalword, removecharacters);
System.out.println(result);
}
}