7

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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
amedeiros
  • 939
  • 2
  • 15
  • 24
  • you mean the first letter of a sentence? – Jf Beaulac Mar 25 '12 at 16:23
  • SOLVED- I solved it by doing the following. I needed it to be sentence[1] and substring(2) for some add reason. sentence = Char.ToUpper(sentence[1]) + sentence.Substring(2); – amedeiros Mar 25 '12 at 16:54
  • Perhaps you might have run `sentence = sentence.Trim();` on it first. There might have been a space before the first letter. – user1934286 Mar 24 '13 at 23:21

2 Answers2

9

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"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
aerb
  • 133
  • 3
  • 8
    You can do this without creating a new CultureInfo - `CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s)` – Blorgbeard Dec 03 '12 at 22:06
  • 5
    This is not the case. TextInfo.ToTitleCase() converts the first letter *of every word* to an upper case character, not just the first letter of the string (sentence in this case), which is what the question is asking for. – Camille Sévigny Jan 20 '15 at 14:20
  • see @Camille Sévigny comment. – Zunair Apr 11 '17 at 17:39
5

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454