ToTitleCase() method is not working with Special Characters

599 views Asked by At

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

2

There are 2 answers

1
Johnathan Barclay On BEST ANSWER

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).

0
Dmitry Bychenko On

Well, ToTitleCase turn 1st letter of each word to upper case while all the other to lower case. Word in terms of .Net is a consequent letters, and, alas, ^ is not a letter, that's why TEST^S consists of 2 words.

We can redefine word as

  • word must start from letter
  • word can contain letters, apostrophes ', circumflexes ^, and full stops .

In this case we can use regular expressions:

  using System.Text.RegularExpressions;

  ... 

  string source = "TEST^S CHECK по-русски (in RUSSIAN) it's a check! a.b.c.d";

  string result = Regex.Replace(source, @"\p{L}[\p{L}\^'\.]*",
    match => match.Value.Substring(0, 1).ToUpper() + match.Value.Substring(1).ToLower());

  Console.Write(result);

Outcome:

  Test^s Check По-Русски (In Russian) It's A Check! A.b.c.d