Monday, July 1, 2013

Write a method to capitalize all vowels in a string (C#)

   
    static void Main(string[] args)
        {
           
            string input = "Clematis require a site that will receive at least one half day of direct sunlight. This helps in bud and bloom production, and in lowering susceptibility to crown rot.   Young clematis are extremely susceptible to crown rot, which is a disease. Crown Rot can usually be prevented by treating the plant with a garden or flower fungicide throughout the growing season.";
            Console.WriteLine (capitalizeVowels(input));
            Console.ReadKey();
            }

First Approach : Using a StringBuilder to hold the intermidiate string.

 public static string capitalizeVowels(string input)
        {
                       if (string.IsNullOrEmpty(input))
                return input;
            else
            {
                HashSet vowels = new HashSet { 'a', 'e', 'i', 'o', 'u' };
                StringBuilder result = new StringBuilder();
                foreach (var i in input)
                {
                    result.Append(vowels.Contains(i) ? char.ToUpper(i) : i);

                }
                return result.ToString();
            }
        }

Second Approach : Using Linq

  public static string capitalizeVowels(string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;
            else
            {
                HashSet vowels = new HashSet { 'a', 'e', 'i', 'o', 'u' };
                return new string(input.Select(x => vowels.Contains(x) ? char.ToUpper(x) : x).ToArray());
            }
        }