7

i want to convert:

HECHT, WILLIAM 

to

Hecht, William

in c#.

any elegant ways of doing this?

leora
  • 188,729
  • 360
  • 878
  • 1,366

5 Answers5

31
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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
5

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
  • 25,263
  • 7
  • 54
  • 64
0
    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
  • 93
  • 3
  • 9
0

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
  • 34,724
  • 14
  • 83
  • 123
-2

I had problems with the code above, so I modified it a bit and it worked. Greetings from Chile. Good paper.

private void label8_Click(object sender, EventArgs e)
{
nombre1.Text= NOMPROPIO(nombre1.Text);
}

string NOMPROPIO(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();
}
Tom Zych
  • 13,329
  • 9
  • 36
  • 53
  • [Please only use English on this site](https://meta.stackexchange.com/questions/13676). For Spanish, there is [Stack Overflow en español](https://es.stackoverflow.com/). – Tom Zych Feb 07 '19 at 19:23