Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a string to have first character uppercase and remainder lowercase

Tags:

c#

I have strings like this:

var a = "abc";
var b = "DEF";
var c = "gHi";

is there a function that I can apply to the string to change it so the first character is an uppercase followed by lowercase?

like image 411
Samantha J T Star Avatar asked Nov 29 '22 03:11

Samantha J T Star


1 Answers

ToTitleCase() is the ideal solution. You can find a link to creating an extension method below. Or for fun you could create one yourself ...

public string ToProperCase(string str)
{
    if (string.IsNullOrEmpty(str))
         return str;

    return str[0].ToUpper() + str.Substring(1).ToLower();
}

// or an extension method
public static string ToProperCase(this string str)
{
    if (string.IsNullOrEmpty(str))
         return str;

    return str[0].ToUpper() + str.Substring(1).ToLower();
}

Link to creating ToTitleCase() as an extension method on System.String:

http://geekswithblogs.net/mucman/archive/2007/03/26/109892.aspx

like image 130
Phil Klein Avatar answered Dec 16 '22 04:12

Phil Klein