Capitalize the firs letter of a string...

  • Thread starter Thread starter DDK
  • Start date Start date
D

DDK

What is the best way to capitalize the first letter of a string?

Thanks for any help,
d.
 
DDK said:
What is the best way to capitalize the first letter of a string?

Thanks for any help,
d.

s = s.Length>0 ? (s[0].ToUpper() + (s.Length>1 ? s.Substring(1, s.Length-1) :
"") : s;
 
DDK said:
What is the best way to capitalize the first letter of a string?

Thanks for any help,
d.

Here's *a* way:

static void Main(string[] args)
{
Console.WriteLine(MakeFirstCharUpperCase("test"));
Console.ReadLine();
}

private static string MakeFirstCharUpperCase(string s)
{
StringBuilder sb = new StringBuilder(s);
sb[0] = Char.ToUpper(sb[0]);
return sb.ToString();
}
 
Thanks for the examples.

I just modified an example I found, I use a label control, as follows:
string strInput = "lowercase";

// if the first char is lower case

if (char.IsLower(strInput[0]))

// capitalize it

strInput = char.ToUpper(strInput[0]) + strInput.Substring(1,
strInput.Length-1);

lblFirstLetterToUpper.Text = strInput.ToString();
 
DDK said:
Thanks for the examples.

I just modified an example I found, I use a label control, as follows:
string strInput = "lowercase";

// if the first char is lower case

if (char.IsLower(strInput[0]))

// capitalize it

strInput = char.ToUpper(strInput[0]) + strInput.Substring(1,
strInput.Length-1);

Here you can use the following instead:

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

This demonstrates another overload of String.Substring() which only
takes one parameter - a start index. In this case, it returns the
sub-string from index 1 to the end of the string.
 
DDK said:
What is the best way to capitalize the first letter of a string?

As well as the previous responses, you may wish to consider the
following if you're doing this a lot - it avoids creating an extra
string unnecessarily:

static string UpperCaseFirstLetter (string original)
{
if (original.Length==0)
{
return original;
}
char originalFirst = original[0];
char upperFirst = char.ToUpper(originalFirst);

if (originalFirst==upperFirst)
{
return original;
}

return upperFirst + original.Substring(1);
}

Note that that will perform the upper casing in the current culture -
you could write another version which specified which culture to use
(and used it in the call to char.ToUpper).
 
Back
Top