tags:

views:

76

answers:

2

I have this function called ProperCase that takes a string, then converts the first letter in each word to uppercase. So ProperCase("john smith") will return "John Smith". Here is the code:

    public string ProperCase(string input)
    {
        var retVal = string.Empty;
        var words = input.Split(' ');

        foreach (var word in words)
        {
            if (word.Length == 1)
            {
                retVal += word.ToUpper();
            }
            else if (word.Length > 1)
            {
                retVal += word.Substring(0, 1).ToUpper() + word.Substring(1).ToLower();
            }

            retVal += ' ';
        }

        if (retVal.Length > 0)
        {
            retVal = retVal.Substring(0, retVal.Length - 1);
        }

        return retVal;
    }

This code workds perfectly, but I'm pretty sure I can do it more elegantly with LINQ and lambdas. Can some please show me how?

+4  A: 

Split the input string into words, convert each word to title case, and join the converted words back together:

TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;

string result = string.Join(" ", input.Split(' ')
                                      .Select(word => textInfo.ToTitleCase(word))
                                      .ToArray());
dtb
Thanks, worked perfectly! I added a ToLower to the lambda:word => textInfo.ToTitleCase(word.ToLower())
Tobias Funke
A: 

Another solution would be

Regex.Replace(input, @"\b\w", m => m.ToString().ToUpper());
Jens