How to Capitalize names

前端 未结 9 1820
余生分开走
余生分开走 2020-12-15 02:46

so basically if i want to transform a name from

stephen smith 

to

Stephen Smith

i can easily do it with c

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 03:11

    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...

提交回复
热议问题