As it turned out during the search, there is a ready-made method System.Globalization.TextInfo.ToTitleCase , which brings the text to the desired form. One problem, the words consisting entirely of capital letters he perceives as abbreviations and skips.
Generally, the title casing converts to the lowercase. However, this method is not currently uppercase, such as an acronym.
To work around, you can reduce the text to lower case, then call this method:
//директива using using System.Globalization; ... var text = "пРиВеТ, мЕНя ЗОвут МАРИНА."; //получаем TextInfo для русского языка var textInfo = new CultureInfo("ru-RU").TextInfo; //преобразуем текст var capitalizedText = textInfo.ToTitleCase(textInfo.ToLower(text)); Console.WriteLine(capitalizedText);
We get:
Hi, My Name is Marina.
Please note that:
- abbreviations will be converted: "FSB" to turn into "FSB";
- word boundaries are determined by non-letter characters: “somewhere” become “Somewhere”;
- capitalization rules depend on locale. In the example above, the
ru-RU locale is used. If it is necessary to take into account the capitalization rules for other languages / regions, changes in the initialization of TextInfo will be required.
The documentation also states that in future versions of .Net, support for linguistically correct capitalization may be added to the method:
It is somewhat simpler and faster. Slower in the future.
The behavior of the method for the Russian locale should not change significantly, but adding additional rules may adversely affect performance.
Other options in the same question in English: Capitalizing words in a string using c # .