格式化字符串文字

时间:2012-11-06 07:26:10

标签: c# .net string

我希望将某个字符串值格式化为first letter所在的Uppercase格式。
例如:

string.Format("{0}", "myName"); //Output must be : "MyName"

我该怎么做?

5 个答案:

答案 0 :(得分:5)

请查看您的个案的MSDN,请参阅TextInfo.ToTitleCase Method

string myString = "wAr aNd pEaCe";        
TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
Console.WriteLine("\"{0}\" to titlecase: {1}", myString, myTI.ToTitleCase(myString));

答案 1 :(得分:3)

如果你只想把第一个字母大写,可能是:

string s = string.Format("{0}", char.ToUpper(myname[0]) + myname.Substring(1));

否则,要将每个单词大写,可以使用TextInfo.ToTitleCase

string s = string.Format("{0}",
    CultureInfo.CurrentCulture.TextInfo.ToTitleCase(myname));

答案 2 :(得分:2)

string test = "myname";
string formatted = System.Globalization.CultureInfo
                         .CurrentUICulture.TextInfo.ToTitleCase(test);

答案 3 :(得分:2)

CultureInfo cultureInfo   = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;

Console.WriteLine("{0}", textInfo.ToTitleCase(myname));

答案 4 :(得分:1)

string input = "myname";
var charArray = input.ToArray();
charArray[0] = char.ToUpper(charArray[0]);

string result = new string(charArray);