I have a string, and I want let the first character capitalize. How to do it?

  • Thread starter Thread starter fAnSKyer/C# newbie
  • Start date Start date
F

fAnSKyer/C# newbie

Sorry for this stupid question.
I am using c way s[0] = s[0] -'a' +'A'

but I can't compile it.

Thanks for your kind help
Best wishes
 
Strings are immutable; you cannot update them. And character
arithmetic isn't very culture safe.

You either need to take the two substrings and use ToUpper() on the
first portion (character), then concatenate, or (depdning on usage)
you might look at TextInfo.ToTitleCase().

Marc
 
fAnSKyer/C# newbie said:
Sorry for this stupid question.
I am using c way s[0] = s[0] -'a' +'A'

but I can't compile it.

Use a StringBuilder instead.
 
Ben Voigt said:
fAnSKyer/C# newbie said:
Sorry for this stupid question.
I am using c way s[0] = s[0] -'a' +'A'

but I can't compile it.

Use a StringBuilder instead.

There's no point in using a StringBuilder here:

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

Okay, there's a box involved, but there won't be any wasted space
(easily avoided with StringBuilder, admittedly), and you won't be
creating a StringBuilder object.
 
Very cool method, works fine. Thanks a lot and all the other fellows:P


Ben Voigt said:
fAnSKyer/C# newbie said:
Sorry for this stupid question.
I am using c way s[0] = s[0] -'a' +'A'
but I can't compile it.
Use a StringBuilder instead.

There's no point in using a StringBuilder here:

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

Okay, there's a box involved, but there won't be any wasted space
(easily avoided with StringBuilder, admittedly), and you won't be
creating a StringBuilder object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top