Search code examples
c#cultureinfocase-conversion

ToTitleCase() method is not working with Special Characters


I have a string that needs to be converted such that it converts first character to Upper case. with ToTitleCase method it works fine except for the case when there is a special characters.

Below is the code and expected result

String textToConvert= "TEST^S CHECK"
TextInfo myTI = new CultureInfo("en-US",false).TextInfo;
       return myTI.ToTitleCase(textToConvert.ToLower())

Expected result: Test^s Check But the result is coming out as Test^S Check with "S" converted to capital after special character ^

Is there anyway to change th conversion to expected result


Solution

  • ToTitleCase is a handy method, but if you need more fine grained control, Regex might be the better option:

    string titleCase = Regex.Replace(textToConvert.ToLower(), @"^[a-z]|(?<= )[a-z]",
        match => match.Value.ToUpper());
    

    ^[a-z]|(?<=\s)[a-z] will match a letter at the start of the string, and letters preceded by whitespace (space, tab or newline).