tags:

views:

7354

answers:

13

Is there an easy way to capitalize the first letter of a string and lower the rest of it? Is there a built in method or do I need to make my own?

+30  A: 

System.Globalization.TextInfo.ToTitleCase().

MSDN Link

ageektrapped
One thing to note here is that it doesn't work if the string is all capitals. It thinks that all caps is an acronym.
Mike Roosa
The thing I have seen with many of these is that you can't rely on them. It wouldn't work if the name is something like McCain or if you start hitting more foreign names.
Mike Wills
@roosa - easy fix for that ToTitleCase(val.ToLower())
Simon_Weaver
+2  A: 

ToTitleCase() should work for you.

http://support.microsoft.com/kb/312890

ckal
+22  A: 
CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello world");
Nathan Baulch
Aww snap! Good answer. I always forget about the globalization stuff.
Michael Haren
A: 

The most direct option is going to be to use the ToTitleCase function that is available in .NET which should take care of the name most of the time. As edg pointed out there are some names that it will not work for, but these are fairly rare so unless you are targeting a culture where such names are common it is not necessary something that you have to worry too much about.

However if you are not working with a .NET langauge, then it depends on what the input looks like - if you have two separate fields for the first name and the last name then you can just capitalize the first letter lower the rest of it using substrings.

firstName = firstName.Substring(0, 1).ToUpper() + firstName.Substring(1).ToLower();
lastName = lastName.Substring(0, 1).ToUpper() + lastName.Substring(1).ToLower();

However, if you are provided multiple names as part of the same string then you need to know how you are getting the information and split it accordingly. So if you are getting a name like "John Doe" you an split the string based upon the space character. If it is in a format such as "Doe, John" you are going to need to split it based upon the comma. However, once you have it split apart you just apply the code shown previously.

Rob
+1  A: 

CultureInfo.CurrentCulture.TextInfo.ToTitleCase ("my name");

returns ~ My Name

But the problem still exists with names like McFly as stated earlier.

David C
McFry! Konichiwa, Mr. Fugitsu-san
Ian Boyd
A: 

If your using vS2k8, you can use an extension method to add it to the String class:

public static string FirstLetterToUpper(this String input)
{
    return input = input.Substring(0, 1).ToUpper() + 
       input.Substring(1, input.Length - 1);
}
FlySwat
`Char.ToUpper(input[0]) + input.Substring(1)` is more readable IMHO.
Hosam Aly
A: 

Like edg indicated, you'll need a more complex algorithm to handle special names (this is probably why many places force everything to upper case).

Something like this untested c# should handle the simple case you requested:

public string SentenceCase(string input)
{
    return input(0, 1).ToUpper + input.Substring(1).ToLower;
}
Michael Haren
Forget this--use the globalization class http://stackoverflow.com/questions/72831/how-do-i-capitalize-first-letter-of-first-name-and-last-name-in-c#72871
Michael Haren
A: 

The suggestions to use ToTitleCase won't work for strings that are all upper case. So you are gonna have to call ToUpper on the first char and ToLower on the remaining characters.

Tundey
Why not call ToLower on the input string before calling ToTitleCase?
Andy Rose
+2  A: 

Mc and Mac are common surname prefixes throughout the US, and there are others. TextInfo.ToTitleCase doesn't handle those cases and shouldn't be used for this purpose. Here's how I'm doing it:

    public static string ToTitleCase(string str)
    {
        string result = str;
        if (!string.IsNullOrEmpty(str))
        {
            var words = str.Split(' ');
            for (int index = 0; index < words.Length; index++)
            {
                var s = words[index];
                if (s.Length > 0)
                {
                    words[index] = s[0].ToString().ToUpper() + s.Substring(1);
                }
            }
            result = string.Join(" ", words);
        }
        return result;
    }
Jamie Ide
+3  A: 

This class does the trick. You can add new prefixes to the _prefixes static string array.

public static class StringExtensions
{
        public static string ToProperCase( this string original )
        {
            if( String.IsNullOrEmpty( original ) )
                return original;

            string result = _properNameRx.Replace( original.ToLower( CultureInfo.CurrentCulture ), HandleWord );
            return result;
        }

        public static string WordToProperCase( this string word )
        {
            if( String.IsNullOrEmpty( word ) )
                return word;

            if( word.Length > 1 )
                return Char.ToUpper( word[0], CultureInfo.CurrentCulture ) + word.Substring( 1 );

            return word.ToUpper( CultureInfo.CurrentCulture );
        }

        private static readonly Regex _properNameRx = new Regex( @"\b(\w+)\b" );
        private static readonly string[] _prefixes = {
                                                         "mc"
                                                     };

        private static string HandleWord( Match m )
        {
            string word = m.Groups[1].Value;

            foreach( string prefix in _prefixes )
            {
                if( word.StartsWith( prefix, StringComparison.CurrentCultureIgnoreCase ) )
                    return prefix.WordToProperCase() + word.Substring( prefix.Length ).WordToProperCase();
            }

            return word.WordToProperCase();
        }
}
guardi
A: 

To get round some of the issues/problems that have ben highlighted I would suggest converting the string to lower case first and then call the ToTitleCase method. You could then use IndexOf(" Mc") or IndexOf(" O\'") to determine sepcial cases that need more specic attention.

inputString = inputString.ToLower();
inputString = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(inputString);
int indexOfMc = inputString.IndexOf(" Mc");
if(indexOfMc  > 0)
{
   inputString.Substring(0, indexOfMc + 3) + inputString[indexOfMc + 3].ToString().ToUpper() + inputString.Substring(indexOfMc + 4);
}
Andy Rose
A: 

hi i Need to capitalize every first character of every word of string "hello my name is shailesh". How will i do it in C#.net08

shailesh
A: 

String test="HELLO HOW ARE YOU" string s =CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test);

The above code wont work .....

so put the below code by convert to lower then apply the function

String test="HELLO HOW ARE YOU"

string s =CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test.ToLower())

Ganesan SubbiahPandian