Digital Colony!

Capitalize the First Letter of a Word in C#

I noticed that a few of my labels in the right column were in lower-case. Since I wrote my own label control, I decided to add a line of code to make sure the first letter in each tag was capitalized.
string labelName;
labelName = char.ToUpper(labelName[0]) + labelName.Substring(1);

Labels: ,

AddThis Social Bookmark Button

6 Comments:

Anonymous Anonymous said...

Yeah, but what if the first name consists of two words. E.g. "Amy Jo"

6/29/2007 11:26 AM

Blogger MAS said...

Split the string into an array (space delimiter) and then run the code on each word and build the string back.

6/29/2007 11:28 AM

Anonymous Anonymous said...

Hi! Heres my Friendly name method used in my base class..
[XmlElement("friendlyname")]
public string FriendlyName
{

get
{
if (_friendlyName == "")
{
//_friendlyName = _name;
//char[] chars = _name.ToCharArray();

_friendlyName = _baseName;
char[] chars = _baseName.ToCharArray();

if (chars.Length > 0)
{

StringBuilder sb = new StringBuilder();
sb.Append(chars[0].ToString().ToUpper());
char lowerBound = 'A';
char upperBound = 'Z';
char spaceChar = ' ';

for (int i = 1; i < chars.Length; i++)
//foreach (char character in chars)
{
if (chars[i] == spaceChar)
{
sb.Append(chars[i].ToString());
continue;
}

if (chars[i - 1] == spaceChar)
chars[i] = Convert.ToChar(chars[i].ToString().ToUpper());

if ((chars[i] >= lowerBound && chars[i] <= upperBound))
{
if (chars[i - 1] != spaceChar)
sb.Append(" ");

sb.Append(chars[i].ToString());
}
else
{
sb.Append(chars[i].ToString());
}
}
_friendlyName = sb.ToString();
}
return _friendlyName;
}
return _friendlyName;
}
set
{
if (_friendlyName != value)
{
_friendlyName = value;
}
}
}
string _friendlyName = "";

7/27/2007 6:15 PM

Anonymous Anonymous said...

using System;
using System.Globalization;

class Test
{
public static void Main ()
{
string s =
CultureInfo.CurrentCulture.TextInfo.ToTitleCase ("i have an apple.");
Console.WriteLine (s);
}
}

8/03/2007 9:44 AM

Blogger Guruuswa said...

you'll d think a language as advanced as C# would have such a basic string function. tut tut microsoft

3/26/2008 6:30 AM

Anonymous Anonymous said...

Behold the power of VB ;)

StrConv(yourTextvalue, VbStrConv.ProperCase)

MSDN on StrConv(

5/19/2008 11:43 PM

 

Post a Comment

 

Digital Colony Copyright © 1999-2008 XHTML   508
This site uses Blogger, which is not 100% XHTML compliant.
Try...Catch Disclaimer: For brevity many examples do not include error handling. That is your responsibility.