Capitalise each word in a sentence using C# .NET
October 9, 2020 2 Comments
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:
Input | Output |
hello world | Hello World |
a beautiful morning | A Beautiful Morning |
the show must go on | The Show Must Go On |
i can’t help falling in love with you | I 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.
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()
);
Thanks for your input, I’ll point to it from the text.