.NET method to convert a string to sentence case

There isn’t anything built in to .NET – however, this is one of those cases where regular expression processing actually may work well. I would start by first converting the entire string to lower case, and then, as a first approximation, you could use regex to find all sequences like [a-z]\.\s+(.), and use ToUpper() to convert the captured group to upper case. The RegEx class has an overloaded Replace() method which accepts a MatchEvaluator delegate, which allows you to define how to replace the matched value.

Here’s a code example of this at work:

var sourcestring = "THIS IS A GROUP. OF CAPITALIZED. LETTERS.";
// start by converting entire string to lower case
var lowerCase = sourcestring.ToLower();
// matches the first sentence of a string, as well as subsequent sentences
var r = new Regex(@"(^[a-z])|\.\s+(.)", RegexOptions.ExplicitCapture);
// MatchEvaluator delegate defines replacement of setence starts to uppercase
var result = r.Replace(lowerCase, s => s.Value.ToUpper());

// result is: "This is a group. Of uncapitalized. Letters."

This could be refined in a number of different ways to better match a broader variety of sentence patterns (not just those ending in a letter+period).

Leave a Comment