2

Possible Duplicates:
Capitalizing word in a string
Make first letter upper case

I have a string like this:

var a = "this is a string";

Is there a simple way I can make the first character change to uppercase?

This is a string

Community
  • 1
  • 1
MIMI
  • 623
  • 2
  • 9
  • 13
  • Your question is actually answered in another question: [Capitalizing word in a string](http://stackoverflow.com/questions/417677/capitalizing-word-in-a-string) – Gabe Aug 29 '11 at 05:19
  • @Gabe, that's not a dupe since it's the first letter in each word. This question _is_ a dupe however, see Drahakar's link. – paxdiablo Aug 29 '11 at 05:20
  • @pax: What I meant is that *the question itself* has the answer to this question. It's not as good as yours, but better than most of the answers in Drahakar's link. – Gabe Aug 29 '11 at 05:22
  • @Gabe: I don't agree with closing questions because the answer is provided in a _different_ question. That just makes answers harder to find. But I'm not overly fussed in this case: I have no doubt this question will be closed, but because there's a duplicate _question._ – paxdiablo Aug 29 '11 at 05:24

2 Answers2

8

You can use the following code:

if (!String.IsNullOrEmpty(a))
    a = Char.ToUpper(a[0]) + a.Substring(1);

If you're sure that the string won't be null or empty, you can drop the if statement as well but I prefer to program defensively.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

If you are not worried about the fact that a string is immutable, than you can return a new string instance.

var a = "this is a string";
a = string.Format("{0}{1}", char.ToUpper(a[0]), a.Remove(0, 1));

But, if you are going to end up needing to do more string manipulation on the same value, you may want to consider using a StringBuilder instead.

var a = "this is a string";
StringBuilder builder = new StringBuilder(a);
builder.Replace(a[0], char.ToUpper(a[0]), 0, 1);
David Anderson
  • 13,558
  • 5
  • 50
  • 76