362

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.

1

24 Answers 24

657

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
17
  • 43
    True. Also, if a word is all upper case it doesn't work. eg - "an FBI agent shot my DOG" - > "An FBI Agent Shot My DOG". And it doesn't handle "McDonalds", and so forth.
    – Kobi
    Commented Jul 30, 2009 at 11:41
  • 5
    @Kirschstein this function does conver these words to title case, even though they shouldn't be in English. See the documentation: Actual result: "War And Peace".
    – Kobi
    Commented Jul 30, 2009 at 11:44
  • 5
    @simbolo - I did actuallt mention it in a comment... You can use something like text = Regex.Replace(text, @"(?<!\S)\p{Ll}", m => m.Value.ToUpper());, but it is far from perfect. For example, it still doesn't handle quotes or parentheses - "(one two three)" -> "(one Two Three)". You may want to ask a new question after you figure out exactly what you want to do with these cases.
    – Kobi
    Commented Nov 11, 2011 at 8:17
  • 19
    For some reason when I have "DR" it doesn't become "Dr" unless I call .ToLower() first before calling ToTitleCase()... So that's something to watch out for... Commented Jan 13, 2014 at 8:18
  • 18
    A .ToLower() to input string is required if the input text is in upper case
    – GeekzSG
    Commented Oct 27, 2014 at 10:18
151

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() );
3
  • 1
    I tried several variations of the TextInfo object - no errors but the original string (upper case) was never updated. Plugged this method in and am very appreciative.
    – justSteve
    Commented Nov 22, 2011 at 19:38
  • 7
    @justSteve, from MSDN (msdn.microsoft.com/en-us/library/…): "However, this method does not currently provide proper casing to convert a word that is entirely uppercase, such as an acronym" - you should probably just ToLower() it first (I know this is old, but just in case someone else stumbles on it and wonders why!)
    – nizmow
    Commented Jan 13, 2014 at 0:27
  • Only available for .NET Framework 4.7.2 <= your frame work <= .NET Core 2.0 Commented Oct 10, 2018 at 22:39
92

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());
3
  • 9
    CultureInfo.InvariantCulture.TextInfo.ToTitleCase(s.ToLower()); would be a better fit actually!
    – GeekzSG
    Commented Oct 27, 2014 at 10:17
  • 1
    Only available for .NET Framework 4.7.2 <= your frame work <= .NET Core 2.0 Commented Oct 10, 2018 at 22:43
  • 5
    Since we are using InvariantCulture for TitleCasing, s.ToLowerInvariant() should be used instead of s.ToLower().
    – Vinigas
    Commented Aug 28, 2019 at 7:25
28

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|
||
|   |
||
10
  • 2
    @harsh : "ugly" solution I would say... makes no sense for me that you have first to convert the whole string to lower-case. Commented Oct 4, 2013 at 11:53
  • 5
    It's intentional, because if you ask for, say, "UNICEF and charity" to be title-cased, you don't want it to be changed to Unicef.
    – Casey
    Commented May 23, 2014 at 14:36
  • 7
    So instead of calling ToLower() on the entire string, you'd rather do all of that work yourself and call the same function on each individual character? Not only is it an ugly solution, it is giving zero benefit, and would even take longer than the built-in function.
    – krillgar
    Commented Jan 29, 2015 at 18:58
  • 3
    rest = words[i].Substring(1).ToLower();
    – krillgar
    Commented Jan 30, 2015 at 15:35
  • 1
    @ruffin No. Substring with a single int parameter starts at the given index, and returns everything to the end of the string.
    – krillgar
    Commented Dec 13, 2019 at 17:19
25

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.

19

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());
    }
18
public static string PropCase(string strText)
{
    return new CultureInfo("en").TextInfo.ToTitleCase(strText.ToLower());
}
1
  • 3
    I like that you added the ToLower prior to ToTitleCase, covers the situation where the input text is all caps.
    – joelc
    Commented Aug 10, 2015 at 4:30
7

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());
1
  • With the string interpolation : return string.Join(" ", text.Split(' ') .Select(i => $"{i.Substring(0, 1).ToUpper()}{i.Substring(1).ToLower()}") .ToArray());
    – Ted
    Commented Nov 21, 2016 at 12:05
6

Here's the solution for that problem...

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

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;
        }
    }

}
2
  • 1
    Just added one more OR condition if (c == ' ' || c == '\'')...sometimes names do contain apostrophes (').
    – JSK
    Commented Nov 27, 2015 at 15:23
  • Perfect! I like it Commented Nov 3, 2022 at 9:25
4

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#

0
2

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());
2

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

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

I wonder why this is not in the answer list: Here is the one liner

string input = "this string will be converted into title case";
    var titleCase = string.Join(" ", input.Split(' ').Select(i => $"{i.Remove(1).ToUpper()}{i.Substring(1).ToLower()}"));
    titleCase.Dump();
Console.WriteLine(titleCase);

this is without any dependency even without using System.Globalization.

Note: If you change the Remove(1) & Substring(1) character from 1 to 2 it will make first two character capital and so on

How it works ?

  1. The input.Remove(1) extracts the first character which is t in the example above and converts it in upper case using ToUpper() which makes T
  2. input.Substring(1) removes the first character from the input in example
  3. The result from 1 & 2 are concerted with $"{} {}" to form the result

How to use

This can be crafted as Func as

Func<string,string> TitleCase = (ins) =>{ 
        return string.Join(" ", ins.Split(' ').Select(i => $"{i.Remove(1).ToUpper()}{i.Substring(1).ToLower()}")); 
    };

Console.WriteLine(TitleCase(input));

Or as an Extension function

public static class StringExt
{
    public static string ToTitleCase(this string input)
    {
        return string.Join(" ", input.Split(' ').Select(i => $"{i.Remove(1).ToUpper()}{i.Substring(1).ToLower()}"));
    }
}

Console.WriteLine(input.ToTitleCase());

enter image description here

5
  • It is not in the answer list because it doesn't answer the question, which was to capitalise the first letter of each word (Proper Case or Title Case), not just the first letter of the sentence/string (Sentence case). Commented Jan 23 at 6:26
  • @SlyGryphon Thanks for pointing that out, see if the updated answer works for you. Commented Jan 23 at 11:58
  • Null check is needed. Otherwise exception will occur Commented Apr 3 at 14:14
  • 1
    @SyedIrfanAhmad Why just null. I expect dev to check if(!string.IsNullOrEmpty("your string")) before calling "your string".ToTitleCase() Commented Apr 9 at 19:28
  • I was randomly testing the string extension method and encountered this exception for string "ASDASAS ASDAS A ASD ADS AS D DASD". Exception was: startIndex cannot be larger than length of string. (Parameter 'startIndex') Commented Apr 16 at 14:17
1
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);
}
1

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.

1

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;
    }
1

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);
}
0

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.

0

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
0

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

0

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();
    }
}
0

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
-1

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.