Convert vowels to uppercase in a string

Given a string – say “hello world”, I was interested in capitalizing the vowels in it – IN A CLEAN & EFFICIENT WAY!

In the first approach, I use a StringBuilder object to hold the intermediate String while in the second approach, I’m using a C# feature – Linq. In the second approach, there is no lazy initialization taking place because we call the toArray() immediately & pass the contents to the String constructor. Looks a lot cleaner! Third approach is simply the best but it’s in Python!

First approach >>

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Output: {0}", CapitalizeWords("hello World"));
            Console.ReadLine();
        }

        static string CapitalizeWords(string input)
        {
            if (string.IsNullOrEmpty(input))
                return string.Empty;

            var sb = new StringBuilder();
            var lookup = new HashSet<Char>() {'a', 'e', 'i', 'o', 'u'};
            foreach (var x in input)
                sb.Append(lookup.Contains(x) ?
                    Char.ToUpper(x) : x);

            return sb.ToString();
        }
    }

Second approach >> much cleaner version using Linq!

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Output: {0}", CapitalizeWords("hello World"));
            Console.ReadLine();
        }

        static string CapitalizeWords(string input)
        {
            if (string.IsNullOrEmpty(input))
                return string.Empty;

            var lookup = new HashSet<Char>() {'a', 'e', 'i', 'o', 'u'};
            return new String(input.Select(x => lookup.Contains(x) ? 
                Char.ToUpper(x) : x).ToArray());
        }
    }

Third approach >> Python takes the cake!

from string import maketrans

def main():
    s = 'hello world'
    print 'Output: {0}'.format(s.translate(maketrans('aeiou', 'AEIOU')))

leave your comment