Capitalizing words in a string using c#

前端 未结 10 1290
攒了一身酷
攒了一身酷 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 12:16

    Depending on how often you plan on doing the capitalization I'd go with the naive approach. You could possibly do it with a regular expression, but the fact that you don't want certain words capitalized makes that a little trickier.

    Edit:

    You can do it with two passes using regexes

    var result = Regex.Replace("of mice and men isn't By CNN", @"\b(\w)", m => m.Value.ToUpper());
    result = Regex.Replace(result, @"(\s(of|in|by|and)|\'[st])\b", m => m.Value.ToLower(), RegexOptions.IgnoreCase);
    

    This outputs Of Mice and Men Isn't by CNN.

    The first expression capitalizes every letter on a word boundary and the second one downcases any words matching the list that are surrounded by whitespace.

    The downsides to this approach is that you're using regexs (now you have two problems) and you'll need to keep that list of excluded words up to date. My regex-fu isn't good enough to be able to do it in one expression, but it might be possible.

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

    Try something like this:

    public static string TitleCase(string input, params string[] dontCapitalize) {
       var split = input.Split(' ');
       for(int i = 0; i < split.Length; i++)
            split[i] = i == 0 
              ? CapitalizeWord(split[i]) 
              : dontCapitalize.Contains(split[i])
                 ? split[i]
                 : CapitalizeWord(split[i]);
       return string.Join(" ", split);
    }
    public static string CapitalizeWord(string word)
    {
        return char.ToUpper(word[0]) + word.Substring(1);
    }
    

    You can then later update the CapitalizeWord method if you need to handle complex surnames. Add those methods to a class and use it like this:

    SomeClass.TitleCase("a test is a sentence", "is", "a"); // returns "A Test is a Sentence"
    
    0 讨论(0)
  • 2020-12-16 12:17

    A non-clever approach that handles the simple case:

    var s = "of mice and men By CNN";
    var sa = s.Split(' ');
    for (var i = 0; i < sa.Length; i++)
        sa[i] = sa[i].Substring(0, 1).ToUpper() + sa[i].Substring(1);
    var sout = string.Join(" ", sa);
    Console.WriteLine(sout);
    
    0 讨论(0)
  • 2020-12-16 12:17

    You should create your own function like you're describing.

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