问题描述
我有一个变量名,说WARD_VS_VITAL_SIGNS,我想将其转换为Pascal大小写格式:WardVsVitalSigns
I have a variable name, say "WARD_VS_VITAL_SIGNS", and I want to convert it to Pascal case format: "WardVsVitalSigns"
WARD_VS_VITAL_SIGNS -> WardVsVitalSigns
我怎样才能让这种转换?
How can I make this conversion?
推荐答案
首先,你所要求的所有权的情况下,而不是骆驼的情况下,因为在骆驼的情况下单词的第一个字母小写,而你的例子显示了你想要的第一个字母。为大写
First off, you are asking for title case and not camel-case, because in camel-case the first letter of the word is lowercase and your example shows you want the first letter to be uppercase.
无论如何,这里是你如何能达到你想要的结果:
At any rate, here is how you could achieve your desired result:
string textToChange = "WARD_VS_VITAL_SIGNS";
System.Text.StringBuilder resultBuilder = new System.Text.StringBuilder();
foreach(char c in textToChange)
{
// Replace anything, but letters and digits, with space
if(!Char.IsLetterOrDigit(c))
{
resultBuilder.Append(" ");
}
else
{
resultBuilder.Append(c);
}
}
string result = resultBuilder.ToString();
// Make result string all lowercase, because ToTitleCase does not change all uppercase correctly
result = result.ToLower();
// Creates a TextInfo based on the "en-US" culture.
TextInfo myTI = new CultureInfo("en-US",false).TextInfo;
result = myTI.ToTitleCase(result).Replace(" ", String.Empty);
请注意:结果
现在 WardVsVitalSigns
。
如果你这样做,其实是想骆驼的情况下,再经过以上所有的,只是用这个帮手功能:
If you did, in fact, want camel-case, then after all of the above, just use this helper function:
public string LowercaseFirst(string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
char[] a = s.ToCharArray();
a[0] = char.ToLower(a[0]);
return new string(a);
}
所以,你可以调用它,就像这样:
So you could call it, like this:
result = LowercaseFirst(result);
这篇关于我如何将文本转换为帕斯卡的情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!