Search code examples
c#.netregexcapitalization

C# Capitalizing string, but only after certain punctuation marks


I'm trying to find an efficient way to take an input string and capitalize the first letter after every punctuation mark (. : ? !) which is followed by a white space.

Input:

"I ate something. but I didn't: instead, no. what do you think? i think not! excuse me.moi"

Output:

"I ate something. But I didn't: Instead, no. What do you think? I think not! Excuse me.moi"

The obvious would be to split it and then capitalize the first char of every group, then concatenate everything. But it's uber ugly. What's the best way to do this? (I'm thinking Regex.Replace using a MatchEvaluator that capitalizes the first letter but would like to get more ideas)

Thanks!


Solution

  • Try this:

    string expression = @"[\.\?\!,]\s+([a-z])";
    string input = "I ate something. but I didn't: instead, no. what do you think? i think not! excuse me.moi";
    char[] charArray = input.ToCharArray();
    foreach (Match match in Regex.Matches(input, expression,RegexOptions.Singleline))
    {
        charArray[match.Groups[1].Index] = Char.ToUpper(charArray[match.Groups[1].Index]);
    }
    string output = new string(charArray);
    // "I ate something. But I didn't: instead, No. What do you think? I think not! Excuse me.moi"