C# Count Vowels

后端 未结 17 1739
小鲜肉
小鲜肉 2020-12-03 08:59

I am learning to program C# and I am trying to count the vowels. I am getting the program to loop through the sentence, but instead of returning vowel count, it is just retu

17条回答
  •  暖寄归人
    2020-12-03 09:21

    TMTOWTDI (Tim Toadie as they say: There's More Than One Way To Do It).

    How about

    static char[] vowels = "AEIOUaeiou".ToCharArray() ;
    public int VowelsInString( string s  )
    {
    
      int n = 0 ;
      for ( int i = 0 ; (i=s.IndexOfAny(vowels,i)) >= 0 ; )
      {
        ++n ;
      }
    
      return n;
    }
    

    Or (another regular expression approach)

    static readonly Regex rxVowels = new Regex( @"[^AEIOU]+" , RegexOptions.IgnoreCase ) ;
    public int VowelCount( string s )
    {
      int n = rxVowels.Replace(s,"").Length ;
      return n ;
    }
    

    The most straightforward is probably the fastest, as well:

    public int VowelCount( string s )
    {
      int n = 0 ;
      for ( int i = 0 ; i < s.Length ; +i )
      {
        switch( s[i] )
        {
        case 'A' : case 'a' :
        case 'E' : case 'e' :
        case 'I' : case 'i' :
        case 'O' : case 'o' :
        case 'U' : case 'u' :
          ++n ;
          break ;
        }
      }
      return n ;
    }
    

提交回复
热议问题