Feedback

C# - Capitalize the first letter of every word

Veröffentlicht von am 7/5/2009
(2 Bewertungen)
You need to format an english sentence into a "headline format" (first letter capitalized).
String words = "this is a totally made-up sentence";
Char splitter = ' '
Capitalize(words, splitter);
splitter = '-'
Capitalize(words, splitter);

private static String Capitalize(String words, Char splitter)
{
    String[] split;

    split = words.Split(splitter);
    words = String.Empty;
    foreach(String part in split)
    {
        Char[] chars;

        chars = part.ToCharArray();
        if(chars.Length > 0)
        {
            chars[0] = ((new String(chars[0], 1)).ToUpper().ToCharArray())[0];
        }
        words += new String(chars) + splitter;
    }
    words = words.Substring(0, words.Length - 1);
    return (words);
}
Abgelegt unter upper case, capitalize, string.

2 Kommentare zum Snippet

Günther Foidl schrieb am 7/6/2009:
Hi,
concatenation of strings should be done by using the StringBuilder instead of simple adding strings together.

Just as comment: The framework has a built-in method for this.

return
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(words);
DJ Doena schrieb am 7/6/2009:
@Günther: Awesome, thx! I looked for something like this, but didn't find it.

:-)
 

Logge dich ein, um hier zu kommentieren!