Capitalise each word in a sentence using C# .NET

Here comes a classic developer interview problem: write a function that takes a string as a parameter and returns the same string with each word in that string capitalised. Examples:

InputOutput
hello worldHello World
a beautiful morningA Beautiful Morning
the show must go onThe Show Must Go On
i can’t help falling in love with youI Can’t Help Falling In Love With You

There are of course multiple solutions to this problem. In this post we’ll go through two of them. Since this blog is mostly dedicated to C# and .NET we’ll use C# but the solutions can easily be translated into other OOP languages.

Note that a third solution based on regex was posted by http://gravatar.com/wkinkeldei in the comment section below.

We can start with a skeleton class and a small set of unit tests.

Capitalise.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Algorithms
{
    public class Capitalise
    {
        public string CapitaliseWordsInSentence(string input)
        {
            return null;
        }        
    }
}

…and a corresponding set of unit tests:

using Algorithms;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Algorithms.Tests
{
    [TestClass]
    public class CapitaliseTests
    {
        [TestMethod]
        public void CapitaliseWordsInSentenceTests()
        {
            Capitalise c = new Capitalise();
            Assert.AreEqual("Hello World", c.CapitaliseWordsInSentence("hello world"));
            Assert.AreEqual("A Beautiful Morning", c.CapitaliseWordsInSentence("a beautiful morning"));
            Assert.AreEqual("The Show Must Go On", c.CapitaliseWordsInSentence("the show must go on"));
            Assert.AreEqual("I Can't Help Falling In Love With You", c.CapitaliseWordsInSentence("i can't help falling in love with you"));
        }        
    }
}

If you run the unit tests then they will of course fail:

Assert.AreEqual failed. Expected:<Hello World>. Actual:<(null)>.

The first possible solution we’ll be looking at is based on a simple iteration. We iterate through each character in the input string. As soon as the character before the current one is equal to an empty space we capitalise the current char. Add the following function to the Capitalise class:

namespace Algorithms
{
    public class Capitalise
    {
        public string CapitaliseWordsInSentence(string input)
        {
            return CapitaliseWordsWithIteration(input);
        }

        private string CapitaliseWordsWithIteration(string input)
        {
            StringBuilder stringBuilder = new StringBuilder(input[0].ToString().ToUpper());
            for (int i = 1; i < input.Length; i++)
            {
                if (input[i - 1] == ' ')
                {
                    stringBuilder.Append(input[i].ToString().ToUpper());
                } else
                {
                    stringBuilder.Append(input[i]);
                }
            }
            return stringBuilder.ToString();
        }     
    }
}

We use a StringBuilder to build the return string character by character. By default we capitalise the first character to begin with. Then we start the iteration from the second character of the input string until its end. If the character before the current one, i.e. at position i - 1 is a whitespace then we capitalise the current char. Otherwise we just add the char to the StringBuilder as-is. Finally we return the final string.

Let’s re-run the unit tests:

OK, good.

Let’s try another approach based on substrings. We split the input string using a whitespace delimiter. Then we iterate through each element in the delimited array. We take the first character of each word, capitalise it, and push the rest of the word to it. We collect the capitalised words in a list which we then use to rebuild the sentence using string.Join. Here’s the function:

private string CapitaliseWordsWithSubstrings(string input)
        {
            List<string> elements = new List<string>();
            foreach(string s in input.Split(' '))
            {               
                elements.Add(s[0].ToString().ToUpper() + s.Substring(1));   
            }

            return string.Join(" ", elements);
        }

If you call this function from CapitaliseWordsInSentence then the tests should pass just like before:

public string CapitaliseWordsInSentence(string input)
{
      return CapitaliseWordsWithSubstrings(input);
     //return CapitaliseWordsWithIteration(input);
}

We can improve the CapitaliseWordsInSentence by adding guards against nulls and empty strings:

public string CapitaliseWordsInSentence(string input)
{
    if (string.IsNullOrEmpty(input))
    {
        return "";
    }
    return CapitaliseWordsWithSubstrings(input);
    //return CapitaliseWordsWithIteration(input);
}

That’s it really.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Capitalise each word in a sentence using C# .NET

  1. wkinkeldei says:

    as a former Perl-hacker, using a Regular expression for this job came into my mind.

    This could be a solution – however, people not using Regexes on a daily basis would probably not recommend using it…

    public string CapitalizeWordsInSentence(string s) =>
    Regex.Replace(
    input: s,
    pattern: “(?:^|\\s)[a-z]”,
    evaluator: m => m.Value.ToUpper()
    );

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: