C# 将所有第一个字母转换为大写,每个单词的其余部分都较低
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1943273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert all first letter to upper case, rest lower for each word
提问by mrblah
I have a string of text (about 5-6 words mostly) that I need to convert.
我有一串文本(大部分大约 5-6 个单词)需要转换。
Currently the text looks like:
目前文本看起来像:
THIS IS MY TEXT RIGHT NOW
I want to convert it to:
我想将其转换为:
This Is My Text Right Now
I can loop through my collection of strings, but not sure how to go about performing this text modification.
我可以遍历我的字符串集合,但不确定如何执行此文本修改。
采纳答案by jspcal
string s = "THIS IS MY TEXT RIGHT NOW";
s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
回答by Jamie Dixon
There's a couple of ways to go about converting the first char of a string to upper case.
有几种方法可以将字符串的第一个字符转换为大写。
The first way is to create a method that simply caps the first char and appends the rest of the string using a substring:
第一种方法是创建一个方法,该方法简单地覆盖第一个字符并使用子字符串附加字符串的其余部分:
public string UppercaseFirst(string s)
{
return char.ToUpper(s[0]) + s.Substring(1);
}
The second way (which is slightly faster) is to split the string into a char array and then re-build the string:
第二种方法(稍微快一点)是将字符串拆分为一个字符数组,然后重新构建字符串:
public string UppercaseFirst(string s)
{
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
回答by ephemient
I don't know if the solution below is more or less efficient than jspcal's answer, but I'm pretty sure it requires less object creation than Jamie's and George's.
我不知道下面的解决方案是否比 jspcal 的答案更有效,但我很确定它比 Jamie 和 George 需要更少的对象创建。
string s = "THIS IS MY TEXT RIGHT NOW";
StringBuilder sb = new StringBuilder(s.Length);
bool capitalize = true;
foreach (char c in s) {
sb.Append(capitalize ? Char.ToUpper(c) : Char.ToLower(c));
capitalize = !Char.IsLetter(c);
}
return sb.ToString();
回答by George Mauer
Untested but something like this should work:
未经测试,但这样的事情应该工作:
var phrase = "THIS IS MY TEXT RIGHT NOW";
var rx = new System.Text.RegularExpressions.Regex(@"(?<=\w)\w");
var newString = rx.Replace(phrase,new MatchEvaluator(m=>m.Value.ToLowerInvariant()));
Essentially it says "preform a regex match on all occurrences of an alphanumeric character that follows another alphanumeric character and then replace it with a lowercase version of itself"
从本质上讲,它说“对跟随另一个字母数字字符的所有字母数字字符进行正则表达式匹配,然后将其替换为自身的小写版本”
回答by Filippo Vitale
I probably prefer to invoke the ToTitleCasefrom CultureInfo(System.Globalization) than Thread.CurrentThread(System.Threading)
我可能更喜欢从CultureInfo( System.Globalization)调用ToTitleCase而不是Thread.CurrentThread( System.Threading)
string s = "THIS IS MY TEXT RIGHT NOW";
s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
but it should be the same as jspcal solution
但它应该与jspcal解决方案相同
EDIT
编辑
Actually those solutions are not the same: CurrentThread
--calls--> CultureInfo
!
实际上,这些解决方案并不相同:CurrentThread
--calls--> CultureInfo
!
System.Threading.Thread.CurrentThread.CurrentCulture
System.Threading.Thread.CurrentThread.CurrentCulture
string s = "THIS IS MY TEXT RIGHT NOW";
s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
IL_0000: ldstr "THIS IS MY TEXT RIGHT NOW"
IL_0005: stloc.0 // s
IL_0006: call System.Threading.Thread.get_CurrentThread
IL_000B: callvirt System.Threading.Thread.get_CurrentCulture
IL_0010: callvirt System.Globalization.CultureInfo.get_TextInfo
IL_0015: ldloc.0 // s
IL_0016: callvirt System.String.ToLower
IL_001B: callvirt System.Globalization.TextInfo.ToTitleCase
IL_0020: stloc.0 // s
System.Globalization.CultureInfo.CurrentCulture
System.Globalization.CultureInfo.CurrentCulture
string s = "THIS IS MY TEXT RIGHT NOW";
s = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
IL_0000: ldstr "THIS IS MY TEXT RIGHT NOW"
IL_0005: stloc.0 // s
IL_0006: call System.Globalization.CultureInfo.get_CurrentCulture
IL_000B: callvirt System.Globalization.CultureInfo.get_TextInfo
IL_0010: ldloc.0 // s
IL_0011: callvirt System.String.ToLower
IL_0016: callvirt System.Globalization.TextInfo.ToTitleCase
IL_001B: stloc.0 // s
References:
参考:
回答by Serj Sagan
When building big tables speed is a concern so Jamie Dixon's second function is best, but it doesn't completely work as is...
当构建大表时,速度是一个问题,因此 Jamie Dixon 的第二个函数是最好的,但它并不能完全按原样工作......
It fails to take all of the letters to lowercase, and it only capitalizes the first letter of the string, not the first letter of each word in the string... the below option fixes both issues:
它无法将所有字母都转换为小写,并且只将字符串的第一个字母大写,而不是字符串中每个单词的第一个字母……以下选项解决了这两个问题:
public string UppercaseFirstEach(string s)
{
char[] a = s.ToLower().ToCharArray();
for (int i = 0; i < a.Count(); i++ )
{
a[i] = i == 0 || a[i-1] == ' ' ? char.ToUpper(a[i]) : a[i];
}
return new string(a);
}
Although at this point, whether this is still the fastest option is uncertain, the Regex
solution provided by George Mauer might be faster... someone who cares enough should test it.
虽然在这一点上,这是否仍然是最快的选择是不确定的,但Regex
乔治·毛尔提供的解决方案可能会更快……有足够关心的人应该测试一下。
回答by M.Eren ?elik
If you're using on a web page, you can also use CSS:
如果你在网页上使用,你也可以使用 CSS:
style="text-transform:capitalize;"
style="text-transform:capitalize;"
回答by zia khan
In addition to first answer, remember to change string selectionstart index to the end of the word or you will get reverse order of letters in the string.
除了第一个答案,记住将字符串 selectionstart 索引更改为单词的末尾,否则您将获得字符串中字母的反向顺序。
s.SelectionStart=s.Length;
回答by Beyondo
Try this technique; It returns the desired result
试试这个技巧;它返回所需的结果
CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
And don't forget to use System.Globalization
.
并且不要忘记使用System.Globalization
.
回答by RShp
One of the possible solution you might be interested in. Traversing an array of chars from right to left and vise versa in one loop.
您可能感兴趣的可能解决方案之一。在一个循环中从右到左遍历字符数组,反之亦然。
public static string WordsToCapitalLetter(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("value");
}
int inputValueCharLength = value.Length;
var valueAsCharArray = value.ToCharArray();
int min = 0;
int max = inputValueCharLength - 1;
while (max > min)
{
char left = value[min];
char previousLeft = (min == 0) ? left : value[min - 1];
char right = value[max];
char nextRight = (max == inputValueCharLength - 1) ? right : value[max - 1];
if (char.IsLetter(left) && !char.IsUpper(left) && char.IsWhiteSpace(previousLeft))
{
valueAsCharArray[min] = char.ToUpper(left);
}
if (char.IsLetter(right) && !char.IsUpper(right) && char.IsWhiteSpace(nextRight))
{
valueAsCharArray[max] = char.ToUpper(right);
}
min++;
max--;
}
return new string(valueAsCharArray);
}