Converting string to title case

C#String

C# Problem Overview


I have a string which contains words in a mixture of upper and lower case characters.

For example: string myData = "a Simple string";

I need to convert the first character of each word (separated by spaces) into upper case. So I want the result as: string myData ="A Simple String";

Is there any easy way to do this? I don't want to split the string and do the conversion (that will be my last resort). Also, it is guaranteed that the strings are in English.

C# Solutions


Solution 1 - C#

MSDN : TextInfo.ToTitleCase

Make sure that you include: using System.Globalization

string title = "war and peace";

TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;

title = textInfo.ToTitleCase(title); 
Console.WriteLine(title) ; //War And Peace

//When text is ALL UPPERCASE...
title = "WAR AND PEACE" ;

title = textInfo.ToTitleCase(title); 
Console.WriteLine(title) ; //WAR AND PEACE

//You need to call ToLower to make it work
title = textInfo.ToTitleCase(title.ToLower()); 
Console.WriteLine(title) ; //War And Peace

Solution 2 - C#

Try this:

string myText = "a Simple string";

string asTitleCase =
    System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.
    ToTitleCase(myText.ToLower());

As has already been pointed out, using TextInfo.ToTitleCase might not give you the exact results you want. If you need more control over the output, you could do something like this:

IEnumerable<char> CharsToTitleCase(string s)
{
	bool newWord = true;
	foreach(char c in s)
	{
		if(newWord) { yield return Char.ToUpper(c); newWord = false; }
		else yield return Char.ToLower(c);
		if(c==' ') newWord = true;
	}
}

And then use it like so:

var asTitleCase = new string( CharsToTitleCase(myText).ToArray() );

Solution 3 - C#

Yet another variation. Based on several tips here I've reduced it to this extension method, which works great for my purposes:

public static string ToTitleCase(this string s) =>
    CultureInfo.InvariantCulture.TextInfo.ToTitleCase(s.ToLower());

Solution 4 - C#

Personally I tried the TextInfo.ToTitleCase method, but, I don´t understand why it doesn´t work when all chars are upper-cased.

Though I like the util function provided by Winston Smith, let me provide the function I'm currently using:

public static String TitleCaseString(String s)
{
    if (s == null) return s;

    String[] words = s.Split(' ');
    for (int i = 0; i < words.Length; i++)
    {
        if (words[i].Length == 0) continue;

        Char firstChar = Char.ToUpper(words[i][0]); 
        String rest = "";
        if (words[i].Length > 1)
        {
            rest = words[i].Substring(1).ToLower();
        }
        words[i] = firstChar + rest;
    }
    return String.Join(" ", words);
}

Playing with some tests strings:

String ts1 = "Converting string to title case in C#";
String ts2 = "C";
String ts3 = "";
String ts4 = "   ";
String ts5 = null;

Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts1)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts2)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts3)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts4)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts5)));

Giving output:

|Converting String To Title Case In C#|
|C|
||
|   |
||

Solution 5 - C#

Recently I found a better solution.

If your text contains every letter in uppercase, then TextInfo will not convert it to the proper case. We can fix that by using the lowercase function inside like this:

public static string ConvertTo_ProperCase(string text)
{
    TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
    return myTI.ToTitleCase(text.ToLower());
}

Now this will convert everything that comes in to Propercase.

Solution 6 - C#

public static string PropCase(string strText)
{
    return new CultureInfo("en").TextInfo.ToTitleCase(strText.ToLower());
}

Solution 7 - C#

Use ToLower() first, and then CultureInfo.CurrentCulture.TextInfo.ToTitleCase on the result to get the correct output.

    //---------------------------------------------------------------
    // Get title case of a string (every word with leading upper case,
    //                             the rest is lower case)
    //    i.e: ABCD EFG -> Abcd Efg,
    //         john doe -> John Doe,
    //         miXEd CaSING - > Mixed Casing
    //---------------------------------------------------------------
    public static string ToTitleCase(string str)
    {
        return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
    }

Solution 8 - C#

If someone is interested for the solution for Compact Framework :

return String.Join(" ", thestring.Split(' ').Select(i => i.Substring(0, 1).ToUpper() + i.Substring(1).ToLower()).ToArray());

Solution 9 - C#

Here's the solution for that problem...

CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
string txt = textInfo.ToTitleCase(txt);

Solution 10 - C#

I needed a way to deal with all caps words, and I liked Ricky AH's solution, but I took it a step further to implement it as an extension method. This avoids the step of having to create your array of chars then call ToArray on it explicitly every time - so you can just call it on the string, like so:

usage:

string newString = oldString.ToProper();

code:

public static class StringExtensions
{
    public static string ToProper(this string s)
    {
        return new string(s.CharsToTitleCase().ToArray());
    }

    public static IEnumerable<char> CharsToTitleCase(this string s)
    {
        bool newWord = true;
        foreach (char c in s)
        {
            if (newWord) { yield return Char.ToUpper(c); newWord = false; }
            else yield return Char.ToLower(c);
            if (c == ' ') newWord = true;
        }
    }

}

Solution 11 - C#

Its better to understand by trying your own code...

Read more

http://www.stupidcodes.com/2014/04/convert-string-to-uppercase-proper-case.html

1) Convert a String to Uppercase

string lower = "converted from lowercase";
Console.WriteLine(lower.ToUpper());

2) Convert a String to Lowercase

string upper = "CONVERTED FROM UPPERCASE";
Console.WriteLine(upper.ToLower());

3) Convert a String to TitleCase

    CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
    TextInfo textInfo = cultureInfo.TextInfo;
    string txt = textInfo.ToTitleCase(TextBox1.Text());

Solution 12 - C#

Here is an implementation, character by character. It should work with "(One Two Three)":

public static string ToInitcap(this string str)
{
    if (string.IsNullOrEmpty(str))
        return str;
    char[] charArray = new char[str.Length];
    bool newWord = true;
    for (int i = 0; i < str.Length; ++i)
    {
        Char currentChar = str[i];
        if (Char.IsLetter(currentChar))
        {
            if (newWord)
            {
                newWord = false;
                currentChar = Char.ToUpper(currentChar);
            }
            else
            {
                currentChar = Char.ToLower(currentChar);
            }
        }
        else if (Char.IsWhiteSpace(currentChar))
        {
            newWord = true;
        }
        charArray[i] = currentChar;
    }
    return new string(charArray);
}

Solution 13 - C#

I used the above references and a complete solution is:

Use Namespace System.Globalization;
string str = "INFOA2Z means all information";

// Need result like "Infoa2z Means All Information"
// We need to convert the string in lowercase also, otherwise it is not working properly.

TextInfo ProperCase = new CultureInfo("en-US", false).TextInfo;

str = ProperCase.ToTitleCase(str.toLower());

Change string to proper case in an ASP.NET Using C#

Solution 14 - C#

String TitleCaseString(String s)
{
    if (s == null || s.Length == 0) return s;

    string[] splits = s.Split(' ');

    for (int i = 0; i < splits.Length; i++)
    {
        switch (splits[i].Length)
        {
            case 1:
                break;

            default:
                splits[i] = Char.ToUpper(splits[i][0]) + splits[i].Substring(1);
                break;
        }
    }

    return String.Join(" ", splits);
}

Solution 15 - C#

You can directly change text or string to proper using this simple method, after checking for null or empty string values in order to eliminate errors:

// Text to proper (Title Case):
    public string TextToProper(string text)
    {
        string ProperText = string.Empty;
        if (!string.IsNullOrEmpty(text))
        {
            ProperText = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);
        }
        else
        {
            ProperText = string.Empty;
        }
        return ProperText;
    }

Solution 16 - C#

Alternative with reference to Microsoft.VisualBasic (handles uppercase strings too):

string properCase = Strings.StrConv(str, VbStrConv.ProperCase);

Solution 17 - C#

Without using TextInfo:

public static string TitleCase(this string text, char seperator = ' ') =>
  string.Join(seperator, text.Split(seperator).Select(word => new string(
    word.Select((letter, i) => i == 0 ? char.ToUpper(letter) : char.ToLower(letter)).ToArray())));

It loops through every letter in each word, converting it to uppercase if it's the first letter otherwise converting it to lowercase.

Solution 18 - C#

Try this:

using System.Globalization;
using System.Threading;
public void ToTitleCase(TextBox TextBoxName)
        {
            int TextLength = TextBoxName.Text.Length;
            if (TextLength == 1)
            {
                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo textInfo = cultureInfo.TextInfo;
                TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
                TextBoxName.SelectionStart = 1;
            }
            else if (TextLength > 1 && TextBoxName.SelectionStart < TextLength)
            {
                int x = TextBoxName.SelectionStart;
                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo textInfo = cultureInfo.TextInfo;
                TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
                TextBoxName.SelectionStart = x;
            }
            else if (TextLength > 1 && TextBoxName.SelectionStart >= TextLength)
            {
                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo textInfo = cultureInfo.TextInfo;
                TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
                TextBoxName.SelectionStart = TextLength;
            }
        }


Call this method in the TextChanged event of the TextBox.

Solution 19 - C#

This is what I use and it works for most cases unless the user decides to override it by pressing shift or caps lock. Like on Android and iOS keyboards.

Private Class ProperCaseHandler
    Private Const wordbreak As String = " ,.1234567890;/\-()#$%^&*€!~+=@"
    Private txtProperCase As TextBox

    Sub New(txt As TextBox)
        txtProperCase = txt
        AddHandler txt.KeyPress, AddressOf txtTextKeyDownProperCase
    End Sub

    Private Sub txtTextKeyDownProperCase(ByVal sender As System.Object, ByVal e As Windows.Forms.KeyPressEventArgs)
        Try
            If Control.IsKeyLocked(Keys.CapsLock) Or Control.ModifierKeys = Keys.Shift Then
                Exit Sub
            Else
                If txtProperCase.TextLength = 0 Then
                    e.KeyChar = e.KeyChar.ToString.ToUpper()
                    e.Handled = False
                Else
                    Dim lastChar As String = txtProperCase.Text.Substring(txtProperCase.SelectionStart - 1, 1)

                    If wordbreak.Contains(lastChar) = True Then
                        e.KeyChar = e.KeyChar.ToString.ToUpper()
                        e.Handled = False
                    End If
                End If

            End If

        Catch ex As Exception
            Exit Sub
        End Try
    End Sub
End Class

Solution 20 - C#

For the ones who are looking to do it automatically on keypress, I did it with following code in VB.NET on a custom textboxcontrol - you can obviously also do it with a normal textbox - but I like the possibility to add recurring code for specific controls via custom controls it suits the concept of OOP.

Imports System.Windows.Forms
Imports System.Drawing
Imports System.ComponentModel

Public Class MyTextBox
    Inherits System.Windows.Forms.TextBox
    Private LastKeyIsNotAlpha As Boolean = True
    Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs)
        If _ProperCasing Then
            Dim c As Char = e.KeyChar
            If Char.IsLetter(c) Then
                If LastKeyIsNotAlpha Then
                    e.KeyChar = Char.ToUpper(c)
                    LastKeyIsNotAlpha = False
                End If
            Else
                LastKeyIsNotAlpha = True
            End If
        End If
        MyBase.OnKeyPress(e)
End Sub
    Private _ProperCasing As Boolean = False
    <Category("Behavior"), Description("When Enabled ensures for automatic proper casing of string"), Browsable(True)>
    Public Property ProperCasing As Boolean
        Get
            Return _ProperCasing
        End Get
        Set(value As Boolean)
            _ProperCasing = value
        End Set
    End Property
End Class

Solution 21 - C#

It works fine even with camel case: 'someText in YourPage'

public static class StringExtensions
{
    /// <summary>
    /// Title case example: 'Some Text In Your Page'.
    /// </summary>
    /// <param name="text">Support camel and title cases combinations: 'someText in YourPage'</param>
    public static string ToTitleCase(this string text)
    {
        if (string.IsNullOrEmpty(text))
        {
            return text;
        }
        var result = string.Empty;
        var splitedBySpace = text.Split(new[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries);
        foreach (var sequence in splitedBySpace)
        {
            // let's check the letters. Sequence can contain even 2 words in camel case
            for (var i = 0; i < sequence.Length; i++)
            {
                var letter = sequence[i].ToString();
                // if the letter is Big or it was spaced so this is a start of another word
                if (letter == letter.ToUpper() || i == 0)
                {
                    // add a space between words
                    result += ' ';
                }
                result += i == 0 ? letter.ToUpper() : letter;
            }
        }
        return result.Trim();
    }
}

Solution 22 - C#

As an extension method:

/// <summary>
//     Returns a copy of this string converted to `Title Case`.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The `Title Case` equivalent of the current string.</returns>
public static string ToTitleCase(this string value)
{
    string result = string.Empty;

    for (int i = 0; i < value.Length; i++)
    {
        char p = i == 0 ? char.MinValue : value[i - 1];
        char c = value[i];

        result += char.IsLetter(c) && ((p is ' ') || p is char.MinValue) ? $"{char.ToUpper(c)}" : $"{char.ToLower(c)}";
    }

    return result;
}

Usage:

"kebab is DELICIOU's   ;d  c...".ToTitleCase();

Result:

Kebab Is Deliciou's ;d C...

Solution 23 - C#

A way to do it in C:

char proper(char string[])
{
    int i = 0;

    for(i=0; i<=25; i++)
    {
        string[i] = tolower(string[i]);  // Converts all characters to lower case
        if(string[i-1] == ' ') // If the character before is a space
        {
            string[i] = toupper(string[i]); // Converts characters after spaces to upper case
        }
    }

    string[0] = toupper(string[0]); // Converts the first character to upper case
    return 0;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNaveenView Question on Stackoverflow
Solution 1 - C#KobiView Answer on Stackoverflow
Solution 2 - C#Winston SmithView Answer on Stackoverflow
Solution 3 - C#Todd MenierView Answer on Stackoverflow
Solution 4 - C#Luis QuijadaView Answer on Stackoverflow
Solution 5 - C#BinodView Answer on Stackoverflow
Solution 6 - C#RajeshView Answer on Stackoverflow
Solution 7 - C#DDanView Answer on Stackoverflow
Solution 8 - C#MibouView Answer on Stackoverflow
Solution 9 - C#JadeView Answer on Stackoverflow
Solution 10 - C#Adam DiamentView Answer on Stackoverflow
Solution 11 - C#Sunil AcharyaView Answer on Stackoverflow
Solution 12 - C#Jeson MartajayaView Answer on Stackoverflow
Solution 13 - C#Rakesh DhimanView Answer on Stackoverflow
Solution 14 - C#varun sharmaView Answer on Stackoverflow
Solution 15 - C#Ashraf SadaView Answer on Stackoverflow
Solution 16 - C#SlaiView Answer on Stackoverflow
Solution 17 - C#mekbView Answer on Stackoverflow
Solution 18 - C#krishnaView Answer on Stackoverflow
Solution 19 - C#Dasith WijesView Answer on Stackoverflow
Solution 20 - C#Andre GotliebView Answer on Stackoverflow
Solution 21 - C#IgorView Answer on Stackoverflow
Solution 22 - C#Ricky SpanishView Answer on Stackoverflow
Solution 23 - C#Daveythewavey19View Answer on Stackoverflow