i want to convert:
HECHT, WILLIAM
to
Hecht, William
in c#.
any elegant ways of doing this?
string name = "HECHT, WILLIAM";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(name.ToLower());
(note it only works lower-to-upper, hence starting lower-case)
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.
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();
}
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.
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();
}