Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize sentence in C# [duplicate]

Tags:

string

c#

char

Possible Duplicate:
How to make a first letter capital in C#

I am trying to capitalize the first word in a sentence. This is what I have, but it is not working.

char.ToUpper(sentence[0]) + sentence.Substring(1)
like image 507
amedeiros Avatar asked Mar 25 '12 16:03

amedeiros


2 Answers

JaredPar's solution is right, but I'd also like to point you towards the TextInfo class. ToTitleCase() will capitalize the first letter, and convert the remaining to lower-case.

        string s = "heLLo";
        var t = new CultureInfo("en-US", false).TextInfo;
        s = t.ToTitleCase(s); // Prints "Hello"
like image 115
aerb Avatar answered Nov 10 '22 17:11

aerb


It sounds like you're just trying to capitalize the first character of a string value. If so then your code is just fine, but you need to assign the new string back into the sentence value.

sentence = char.ToUpper(sentence[0]) + sentence.Substring(1)

A string in .NET is immutable and hence every operation which changes the string produces a new value. It won't change the original value in place. So in order to see the result of the change, you must assign it into a variable.

like image 35
JaredPar Avatar answered Nov 10 '22 16:11

JaredPar