Use string methods to find and count vowels in a string?

前端 未结 9 2062
青春惊慌失措
青春惊慌失措 2020-12-02 02:04

I have this problem for homework (I\'m being honest, not trying to hide it at least) And I\'m having problems figuring out how to do it.

Given the following declarat

相关标签:
9条回答
  • 2020-12-02 02:34

    This could/should be a one-liner

    System.out.println("the count of all vowels: " + (phrase.length() - phrase.replaceAll("a|e|i|o|u", "").length()));
    

    and its String only methods

    0 讨论(0)
  • 2020-12-02 02:41

    phrase.substring(i, i++); should be phrase.substring(i, i + 1);.

    i++ gives the value of i and then adds 1 to it. As you have it right now, String j is effectively phrase.substring(i, i);, which is always the empty string.

    You don't need to change the value of i in the body of the for loop since it is already incremented in for (i = 0; i < length; i++).

    0 讨论(0)
  • 2020-12-02 02:41

    Using Collections:

         String word = "busiunesuse";
         char[] wordchar= word.toCharArray();
         Character allvowes[] ={'a','e','i','o','u'};
         Map<Character, Integer> mymap = new HashMap();
    
         for(Character ch: wordchar)
         {
             for(Character vowels : allvowes)
             {
                if(vowels.equals(ch))
                {
                 if(mymap.get(ch)== null)
                 {
                     mymap.put(ch, 1);
                 }
                 else
                 {
                     int val = mymap.get(ch);
                     mymap.put(ch, ++val);
                 }
                }
    
             }
         }
    
         Set <Character> myset = mymap.keySet();
         Iterator myitr = myset.iterator();
    
         while(myitr.hasNext())
         {
             Character key = (Character) myitr.next();
             int value = mymap.get(key);
             System.out.println("word:"+key+"repetiotions:"+value);
    
    
         }
    
    
    }
    

    }

    0 讨论(0)
提交回复
热议问题