C#首字母大写字母 - 更有效的方法?

时间:2015-10-19 03:36:40

标签: c# parsing

我有一些代码可以完成我想要它做的事情,但我想知道是否有更快的方法来做我想要的事情。

用户将输入他们的名字,我想确保他们的名字尽可能接近这种格式:

  • john>约翰
  • julie>朱莉

我的代码:

// First Name
s_in_GetUserFirstName = s_in_GetUserFirstName.ToLower();
c_in_UserFirstNameFirstChar = s_in_GetUserFirstName[0];
s_in_UserFirstNameFirstChar = c_in_UserFirstNameFirstChar.ToString().ToUpper();
s_in_GetUserFirstName = s_in_GetUserFirstName.Remove(0, 1);
s_in_GetUserFirstName = s_in_UserFirstNameFirstChar + s_in_GetUserFirstName;
// Last Name
s_in_GetUserLastName = s_in_GetUserLastName.ToLower();
c_in_UserLastNameFirstChar = s_in_GetUserLastName[0];
s_in_UserLastNameFirstChar = c_in_UserLastNameFirstChar.ToString().ToUpper();
s_in_GetUserLastName = s_in_GetUserLastName.Remove(0, 1);
s_in_GetUserLastName = s_in_UserLastNameFirstChar + s_in_GetUserLastName;

我所做的是将字符串分成两部分,第一部分和其余部分。我将第一个字符大写并从字符串中删除该字符。然后我将字符串合并为一个。

1 个答案:

答案 0 :(得分:0)

您可以在一行中执行此操作

test.Substring(0,1).ToUpper()+test.Substring(1);

或者像Rob在评论中所建议的那样这样做

Converting string to title case