C# Capitalize first letter in in each sentence in a string

Viewed 8926

I want to capitalize the first letter of each sentence in a string. I have a string, ex. "hello, how are you? i'm fine, you? i'm good. nice weather!"

and I want to capitalize the first letter of each sentence in it. So, "Hello, how are you? I'm fine, you?" etc.

EDIT: So far, I've just tried

public static string FirstCharToUpper(string input)
        {
            if (String.IsNullOrEmpty(input))
                throw new ArgumentException("ARGH!");
            return input.First().ToString().ToUpper() + input.Substring(1);
        }

but this capitalizes the first letter in each word, not sentence :/

5 Answers

It's been stated a few times, iterate over the character array. The primary reason for this is it keeps the string structure vs say a split, toupper/substring, and join.

Below handles a few scenarios, such as don't capitalize a letter after a digit. It also makes some assumptions in addition to those described/solved for above, hope it helps.

public static string CapitalizeFirstLetterInEachSentence(string sentences, bool capitalizeFirstSentence = true)
{
  bool capitalizeNextLetterOrDigit = capitalizeFirstSentence;
  char[] characters = sentences.ToCharArray();
  var len = characters.Length;

  for (int i = 0; i < len; i++)
  {
    var character = characters[i];
    switch (character)
    {
      case '.':
      case '?':
      case '!':
        capitalizeNextLetterOrDigit = true;
        continue;
    }
    
    if (capitalizeNextLetterOrDigit && char.IsLetterOrDigit(character))
    {
      capitalizeNextLetterOrDigit = false;
      characters[i] = char.ToUpper(character);
    }
  }
  return new string(characters);
}
Related