HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Capitalize words in sentence

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sentencewordscapitalize

Problem

public static class StringHelpers
{
    public static string CapitalizeEachWord(this string sentence)
    {
        CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
        TextInfo textInfo = cultureInfo.TextInfo;

        if (String.IsNullOrEmpty(sentence))
        {
            return String.Empty;
        }

        return textInfo.ToTitleCase(sentence);
    }

    public static string CapitalizeFirstWord(this string sentence)
    {
        if (String.IsNullOrEmpty(sentence))
        {
            return String.Empty;
        }

        var words = sentence.Split();
        StringBuilder resultBuilder = new StringBuilder();

        var letters = words[0].ToCharArray();
        List lettersHolder = new List();
        lettersHolder.Add(letters[0].ToString().ToUpper());
        for (int i = 1; i < letters.Length; i++)
        {
            lettersHolder.Add(letters[i].ToString().ToLower());
        }

        foreach (var letter in lettersHolder)
        {
            resultBuilder.Append(letter);                   
        }

        resultBuilder.Append(" ");

        for (int i = 1; i < words.Length; i++)
        {
            resultBuilder.Append(words[i].ToLower());
            resultBuilder.Append(" ");
        }

        return resultBuilder.ToString();
    }
}


The first method, is supposed to correctly capitalize each word in a sentence. I don't think there's much room for improvement in that one.

The second method, seems a little confusing and even after I've written it and tested it, I cannot seem to fully put what it's doing into my buffer. That's a sign of code smell.

If I kinda get it now, what will happen down the line when I have to change it or something.

Solution

You're right, your second method is way too complicated. It also doesn't handle the case where the string starts with a space (in which case words[0] will be the empty string and letters[0] will be out of bounds). Since all your method seems to be doing is to capitalize the first letter of the string and lower case everything else, why not just do that?

public static string CapitalizeFirstWord(this string sentence)
{
    if (String.IsNullOrEmpty(sentence))
    {
        return String.Empty;
    }

    String firstLetter = sentence.Substring(0,1);
    String rest = sentence.Substring(1);
    return firstLetter.ToUpper() + rest.ToLower();
}

Code Snippets

public static string CapitalizeFirstWord(this string sentence)
{
    if (String.IsNullOrEmpty(sentence))
    {
        return String.Empty;
    }

    String firstLetter = sentence.Substring(0,1);
    String rest = sentence.Substring(1);
    return firstLetter.ToUpper() + rest.ToLower();
}

Context

StackExchange Code Review Q#900, answer score: 10

Revisions (0)

No revisions yet.