简体   繁体   中英

How do I capitalized any two letter word in a string in addition to the first letter of any word?

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.

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

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

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;
}
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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM