开发者

Use LINQ and lambdas to put string in proper case

开发者 https://www.devze.com 2022-12-26 13:49 出处:网络
I have this function called ProperCase that takes a st开发者_如何学Pythonring, then converts the first letter in each word to uppercase.So ProperCase(\"john smith\") will return \"John Smith\".Here is

I have this function called ProperCase that takes a st开发者_如何学Pythonring, 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?


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());


Another solution would be

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


Based on dtb's answer. If you are dealing with c# razor in an cshtml page and need a one liner:

@(string.Join(" ", input.ToLower().Split(' ').Select(word => word.Substring(0,1).ToUpper() + word.Substring(1, word.Length - 1)).ToArray() ))

Or Javascript (could use regex, but this was fun figuring out):

var text = input.toLowerCase().split(' ').map(function(word){ return word.substring(0, 1).toUpperCase() + word.substring(1, word.length); }).join(" ");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号