Reputation: 3977
I need to capitalized the first letter of each word in a string and also capitalized both letters the string if the length of the word is two.
Example input:
dr. david BOWIE md
Example Output:
Dr. David Bowie MD
I started of with something like this:
TextInfo tCase = new CultureInfo("en-US", false).TextInfo;
return tCase.ToTitleCase(input.ToLower());
Not sure how to pull this off.
Upvotes: 1
Views: 146
Reputation: 11233
I would extend your solution with Regex to a one linear solution:
string result = Regex.Replace(new CultureInfo("en-US", false).TextInfo.ToTitleCase(input.ToLower()), @"(?i)\b([a-z]{2})(?!.)\b", m => m.ToString().ToUpper());
Console.WriteLine(result);
Output:
Dr. David Bowie MD
Upvotes: 0
Reputation: 59252
You can do this:
TextInfo tCase = new CultureInfo("en-US", false).TextInfo;
string s = "dr. david BOWIE md";
var ss = string.Join(" ", s.Split(' ').Select(u => u.Length == 2 ? u.ToUpper() : tCase.ToTitleCase(u.ToLower())).ToList());
Console.WriteLine(ss);
Outputs:
Dr. David Bowie MD
Upvotes: 0
Reputation: 3966
var str = "dr. david BOWIE md";
var strList = new List<string>();
str.Split(' ').ToList().ForEach(s =>
{
strList.Add(s.Length == 2 ? s.ToUpper() : string.Format("{0}{1}", char.ToUpper(s[0]), s.Substring(1).ToLower()));
});
var output = string.Join(" ", strList.ToArray());
Console.WriteLine(output);
OUTPUT:
Dr. David Bowie MD
Upvotes: 0
Reputation: 3363
String s = "dr. david BOWIE md";
s= ConvertToMyCase(s);
public string ConvertToMyCase(string s)
{
s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.toLower());
List<string> my = new List<string>();
string[] separators = new string[] {",", ".", "!", "\'", " ", "\'s"};
foreach (string word in s.Split(separators, StringSplitOptions.RemoveEmptyEntries))
{
if(word.Length == 2)
{
word.ToUpper();
}
}
return s;
}
Upvotes: 0
Reputation: 11840
You could try this, using Split
and Join
:
var input = "dr. david BOWIE md";
TextInfo tCase = new CultureInfo("en-US", false).TextInfo;
var result = tCase.ToTitleCase(input.ToLower());
result = string.Join(" ", result.Split(' ')
.Select(i => i.Length == 2 ? i.ToUpperInvariant() : i));
Output:
Dr. David Bowie MD
Upvotes: 2