Home » c# » Is there a native Proper Case string function in C#? [duplicate]

Is there a native Proper Case string function in C#? [duplicate]

Posted by: admin December 21, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

There is a function that capitalises the first letters of words, though you should see the remarks section as it does have some limitations which may make it unsuitable for your needs.

Questions:
Answers:
String s  = "yOu caN Use thIs"

s = System.Threading.Thread.CurrentThread
           .CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

The main limitation I can see with this is that it’s not “true” title case. i.e. In the phrase “WaR aNd peaCe”, the “and” part should be lowercase in English. This method would capitalise it though.

Questions:
Answers:

you can just add some exten­sion meth­ods to the Sting type:

public static class StringExtension
{
    /// <summary>
    /// Use the current thread's culture info for conversion
    /// </summary>
    public static string ToTitleCase(this string str)
    {
        var cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
        return cultureInfo.TextInfo.ToTitleCase(str.ToLower());
    }

    /// <summary>
    /// Overload which uses the culture info with the specified name
    /// </summary>
    public static string ToTitleCase(this string str, string cultureInfoName)
    {
        var cultureInfo = new CultureInfo(cultureInfoName);
        return cultureInfo.TextInfo.ToTitleCase(str.ToLower());
    }

    /// <summary>
    /// Overload which uses the specified culture info
    /// </summary>
    public static string ToTitleCase(this string str, CultureInfo cultureInfo)
    {
        return cultureInfo.TextInfo.ToTitleCase(str.ToLower());
    }
}

Questions:
Answers:

This works

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

Questions:
Answers:

This should work.

public static string ToTitleCase(this string strX)
{
    string[] aryWords = strX.Trim().Split(' ');

    List<string> lstLetters = new List<string>();
    List<string> lstWords = new List<string>();

    foreach (string strWord in aryWords)
    {
        int iLCount = 0;
        foreach (char chrLetter in strWord.Trim())
        {
            if (iLCount == 0)
            {
                lstLetters.Add(chrLetter.ToString().ToUpper());
            }
            else
            {
                lstLetters.Add(chrLetter.ToString().ToLower());
            }
            iLCount++;
        }
        lstWords.Add(string.Join("", lstLetters));
        lstLetters.Clear();
    }

    string strNewString = string.Join(" ", lstWords);

    return strNewString;
}