Capitalizing words in a string using c#

前端 未结 10 1289
攒了一身酷
攒了一身酷 2020-12-16 11:22

I need to take a string, and capitalize words in it. Certain words (\"in\", \"at\", etc.), are not capitalized and are changed to lower case if encountered. The first word s

相关标签:
10条回答
  • 2020-12-16 11:51

    A slight improvement on jonnii's answer:

    var result = Regex.Replace(s.Trim(), @"\b(\w)", m => m.Value.ToUpper());
            result = Regex.Replace(result, @"\s(of|in|by|and)\s", m => m.Value.ToLower(), RegexOptions.IgnoreCase);
            result = result.Replace("'S", "'s");
    
    0 讨论(0)
  • 2020-12-16 11:59

    The easiest obvious solution (for English sentences) would be to:

    • "sentence".Split(" ") the sentence on space characters
    • Loop through each item
    • Capitalize the first letter of each item - item[i][0].ToUpper(),
    • Remerge back into a string joined on a space.
    • Repeat this process with "." and "," using that new string.
    0 讨论(0)
  • 2020-12-16 12:03

    Use

    Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase("of mice and men By CNN");
    

    to convert to proper case and then you can loop through the keywords as you have mentioned.

    0 讨论(0)
  • 2020-12-16 12:07

    Here is answer How to Capitalize names

    CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
    TextInfo textInfo = cultureInfo.TextInfo;
    
    Console.WriteLine(textInfo.ToTitleCase(title));
    Console.WriteLine(textInfo.ToLower(title));
    Console.WriteLine(textInfo.ToUpper(title));
    
    0 讨论(0)
  • 2020-12-16 12:12

    You can have a Dictionary having the words you would like to ignore, split the sentence in phrases (.split(' ')) and for each phrase, check if the phrase exists in the dictionary, if it does not, capitalize the first character and then, add the string to a string buffer. If the phrase you are currently processing is in the dictionary, simply add it to the string buffer.

    0 讨论(0)
  • 2020-12-16 12:14

    Why not use ToTitleCase() first and then keep a list of applicable words and Replace back to the all-lower-case version of those applicable words (provided that list is small).

    The list of applicable words could be kept in a dictionary and looped through pretty efficiently, replacing with the .ToLower() equivalent.

    0 讨论(0)
提交回复
热议问题