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

4
  • Your question is actually answered in another question: Capitalizing word in a string Commented Aug 29, 2011 at 5: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. Commented Aug 29, 2011 at 5: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. Commented Aug 29, 2011 at 5: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. Commented Aug 29, 2011 at 5:24

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.