so basically if i want to transform a name from
stephen smith
to
Stephen Smith
i can easily do it with c
This works for me with surnames that have a ' character in them.
if (Surname.Contains("'"))
{
String[] Names = Surname.Split('\'').ToArray();
Surname = textInfo.ToTitleCase(Names[0].ToString());
Surname += "''";
Surname += textInfo.ToTitleCase(Names[1].ToString());
}
A slight extension on the answer offered by Pedro:
Regex.Replace(Name, @"(?:(M|m)(c)|(\b))([a-z])", delegate(Match m) {
return String.Concat(m.Groups[1].Value.ToUpper(), m.Groups[2].Value, m.Groups[3].Value, m.Groups[4].Value.ToUpper());
});
This will correctly capitalize McNames in addition to title case. eg "simon mcguinnis" --> "Simon McGuinnis"
If it matches "Mc" or "mc" the groups 1 and 2 contain "m" and "c" and group 3 is empty.
All 4 groups, empty or otherwise, are concatenated to generate the return string.
This is an extension method on the string class that capitalizes a single word. You can use it alongside a str.Split()
and str.Join
to capitalize every word of the str
string. You can add checks for empty or one character length strings.
public static string Capitalize(this string word)
{
return word.Substring(0, 1).ToUpper() + word.Substring(1).ToLower();
}
Hope this helps :)... But note that the process will most likely be slow if you have many, many strings to change case...
string str = "to title case";
Char[] ca = str.ToCharArray();
foreach(Match m in Regex.Matches(str, @"\b[a-z]"))
{
ca[m.Index] = Char.ToUpper(ca[m.Index]);
}
Console.WriteLine(new string(ca));
Update: Or you could also use a custom evaluator to change the case like this:
string str = "to title case";
Console.WriteLine(Regex.Replace(str, @"\b[a-z]", delegate (Match m)
{
return m.Value.ToUpper();
}
));
Note that in my test with 1,000,000 iterations the first method was only 0.48 seconds faster than the one with the evaluator (The first one took 6.88 seconds and the latter 7.36 seconds to complete the 1,000,000 iterations) so I wouldn't take speed into account to choose either...
You can do this using the ToTitleCase
method of the System.Globalization.TextInfo class:
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
Console.WriteLine(textInfo.ToTitleCase(title));
Console.WriteLine(textInfo.ToLower(title));
Console.WriteLine(textInfo.ToUpper(title));
Names are tricky. The simple rules of First Letters do not apply. The only sensible approach here is to ask your users how they want it. Anything else can cause offence.
If my name is MacPhearson, ODowel, or just simply marc, Marc or even mArC - then frankly: leave it alone. Trust the user to get it right. This gets even more tricky as you go between cultures.