使用java中的子字符串从字符串中删除元音

时间:2015-09-22 12:52:27

标签: java

 public class Vowels {
    public static void main(String[] args) {
        char []a={'a','e','i','o','u','e'};
        String line="abcee";
        for (char c : a) {
            for (int i = 0; i < a.length; i++) {
                if (line.charAt(i)==c) {
                    line=line.substring(0, i)+line.substring(i+1);
                }
            }
        }
        System.out.println(line);
    }
}

这个代码的错误多于相同的元音没有删除。

5 个答案:

答案 0 :(得分:2)

此代码将从任何String中删除A E I O和U.此代码来自Writing a method to remove vowels in a Java String,对于使用循环的解决方案,请参阅Remove all vowels in a string with Java

public static void main(String[] args) {
    String line = "abcee";

    line = line.replaceAll("[AEIOUaeiou]", "");

    String alphabet = "abcdefghijklmnopqrstuvwxyz";

    alphabet = alphabet.replaceAll("[AEIOUaeiou]", "");

    System.out.println(line);

    System.out.println(alphabet);
}

输出:

  

BC

     

bcdfghjklmnpqrstvwxyz

答案 1 :(得分:1)

有两个问题:

  • 切换循环的顺序(现在,如果您有两个相同的元音,则不会删除第二个元音)。
  • a.length更改为line.length()
for (int i = 0; i < line.length(); i++)
  for (char c : a)

答案 2 :(得分:1)

试试这个(虽然使用子字符串有点奇怪):

public class Vowels {
public static void main(String[] args) {
    char []a={'a','e','i','o','u','e'};
    String line="abcee";

    for (char c : a) {
        while(line.indexOf(c) > -1){
            line = line.substring(0, line.indexOf(c)) + line.substring(0, line.indexOf(c)+1); 
        }
    }
    System.out.println(line);
 }

}

答案 3 :(得分:0)

试试这个:

public static void main(String[] args){
    String[] a = { "a", "e", "i", "o", "u" };
    ArrayList<String> vowels = new ArrayList<String>();
    vowels.addAll(Arrays.asList(a));
    String line = "abceesdfdsfewereraerwe";
    for (int i = 0; i < line.length(); i++) {
            String val = String.valueOf(line.charAt(i));
            if (vowels.contains(val)) {
                line = line.replace(val, "");
            }
        }
    System.out.println(line);
    }
}

答案 4 :(得分:0)

您可以使用PatternMatcher

    String str = "abceeuoopqr";
    Pattern pattern = Pattern.compile("[aeioue]");
    Matcher matcher = pattern.matcher(str);
    if(matcher.find()){
        System.out.println(matcher.replaceAll(""));
    }