删除字符串中的重复元音

时间:2017-08-07 09:45:52

标签: java string

这是程序任何人都可以帮助我 起初我给了字符串第一部分工作正常它在字符串中找到元音并打印

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String a = "History can also refer to the academic discipline ";
    int count = 0;

    for (int i = 0; i < a.length(); i++) {  

        if (a.charAt(i) == 'a' || a.charAt(i) == 'e' || a.charAt(i) == 'i' || a.charAt(i) == 'u'
                || a.charAt(i) == 'u') {
            System.out.println("The sentence have vowels:" + a.charAt(i));
            count++;//counting the number of vowels
        }
        if (a.charAt(i+1) == 'a' || a.charAt(i+1) == 'e' || a.charAt(i+1) == 'i' || a.charAt(i+1) == 'u'
                || a.charAt(i+1) == 'u') {i++;}//finding reoccurring vowels 
    }
    System.out.println("number of vowels:" + count);
}

}

在第二部分我试图跳过重复发生的元音,但它不起作用

2 个答案:

答案 0 :(得分:0)

您需要进行一些更改:

  • 运行循环直到a.length() - 1,因为您已经在循环中检查i+1个字符
  • 如果不满足第二个if条件,则重置计数。

e.g:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String a = "History can also refer to the academic discipline ";
    int count = 0;

    for (int i = 0; i < a.length() - 1; i++) {  

        if (a.charAt(i) == 'a' || a.charAt(i) == 'e' || a.charAt(i) == 'i' || a.charAt(i) == 'u'
                || a.charAt(i) == 'u') {
            System.out.println("The sentence have vowels:" + a.charAt(i));
            count++;//counting the number of vowels
        }
        //finding reoccurring vowels
        if (a.charAt(i+1) == 'a' || a.charAt(i+1) == 'e' || a.charAt(i+1) == 'i' || a.charAt(i+1) == 'u'
                || a.charAt(i+1) == 'u') {
            i++;
         } else{
            count = 0;
         } 
    }
    System.out.println("number of vowels:" + count);
}

答案 1 :(得分:0)

这个怎么样

    public static void main(String[] args) {
    String a = "History can also refer to the academic discipline ";
    int count = 0;

    boolean lastWasVowel = false;

    for (int i = 0; i < a.length(); i++) {

        if (a.charAt(i) == 'a' || a.charAt(i) == 'e' || a.charAt(i) == 'i' || a.charAt(i) == 'o'
                || a.charAt(i) == 'u') {
            if(!lastWasVowel) {
                count++;
            }
            lastWasVowel = true;
         } else {
            lastWasVowel = false;
        }
     }
    System.out.println("number of vowels:" + count);
}