Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalizing the first letter of a string only [duplicate]

Tags:

string

c#

asp.net

I have already taken a look at such posts like:

Format to first letter uppercase
How to capitalise the first letter of every word in a string

But none of these seem to actually work. I would have thought to start with that there would just be a:

.Capitalize();

Like there is:

.Lower(); & .Upper();

Are there any documentation or references regarding converting to a string like the following?

string before = "INVOICE";

To then becoming:

string after = "Invoice";

I receive no errors using the way the posts solutions I read give me, however, the before still remains capitalized.

like image 708
Jaquarh Avatar asked Feb 22 '16 09:02

Jaquarh


2 Answers

What about using ToUpper on the first char and ToLower on the remaining string?

string after = char.ToUpper(before.First()) + before.Substring(1).ToLower();
like image 182
Patrick Hofman Avatar answered Oct 11 '22 09:10

Patrick Hofman


You can create a method that does something like this:

string UppercaseFirst(string str)
{
    if (string.IsNullOrEmpty(str))
        return string.Empty;
    return char.ToUpper(str[0]) + str.Substring(1).ToLower();
}

And use it like this:

string str = "thISstringLOokSHorribLE";
string upstr = UppercaseFirst(str);

to get this:

Thisstringlookshorrible
like image 45
Ian Avatar answered Oct 11 '22 09:10

Ian