tags:

views:

337

answers:

4

i want to convert:

HECHT, WILLIAM

to

Hecht, William

in c#.

any elegant ways of doing this?

+25  A: 
string name = "HECHT, WILLIAM";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(name.ToLower());

(note it only works lower-to-upper, hence starting lower-case)

Marc Gravell
Is that thing in there? Oh my. +1
Martinho Fernandes
@Marc: Does `ToTitleCase()` handle "Peter O'Toole" and "Mary Jones-Smith" properly?
Grant Wagner
@Grant: Peter needs a new name, Mary is fine though.
Fredrik Mörk
A: 
    public static string CamelCase(this string s)
    {
        if (String.IsNullOrEmpty(s))
            s = "";
        string phrase = "";
        string[] words = s.Split(' ');
        foreach (string word in words)
        {
            if (word.Length > 1)
                phrase += word.Substring(0, 1).ToUpper() + word.Substring(1).ToLower() + " ";
            else
                phrase += word.ToUpper() + " ";

        }
        return phrase.Trim();
    }
TruthStands
@TruthStands: Does not produce the correct results for "Peter O'Toole" and "Mary Smith-Jones".
Grant Wagner
True, but it would not be difficult to fix that.
TruthStands
A: 

I voted Marc's answer up, but this will also work:

string s = Microsoft.VisualBasic.Strings.StrConv("HECHT, WILLIAM", VbStrConv.ProperCase,0);

You'll need to add the appropriate references, but I'm pretty sure it works on all-upper inputs.

richardtallent
+2  A: 

I'd just like to include an answer that points out that although this seems simple in theory, in practice properly capitalizing the names of everyone can be very complicated:

Anyway, just something to think about.

Grant Wagner