我有一个带有文本框的DetailsView
我希望输入的数据总是以大写的第一个字母保存。
例子:
"red" --> "Red"
"red house" --> " Red house"
我怎样才能实现性能最大化呢?
注意:
Based on the answers and the comments under the answers, many people think this is asking about capitalizing all words in the string. E.g. => Red House It isn't, but if that is what you seek, look for one of the answers that uses TextInfo's ToTitleCase method. (Note: Those answers are incorrect for the question actually asked.)
See TextInfo.ToTitleCase documentation for caveats (doesn't touch all-caps words - they are considered acronyms; may lowercase letters in middle of words that "shouldn't" be lowered, e.g., "McDonald" → "Mcdonald"; not guaranteed to handle all culture-specific subtleties re capitalization rules.)
注意:
第一个字母之后的字母是否必须小写,这个问题很模糊。公认的答案假定只有第一个字母需要修改。如果要强制字符串中除第一个字母外的所有字母都小写,请查找包含ToLower且不包含ToTitleCase的答案。
我从c#大写首字母- Dot Net Perls中获得了最快的方法,并将其转换为扩展方法:
/// <summary>
/// Returns the input string with the first character converted to uppercase, or mutates any nulls passed into string.Empty
/// </summary>
public static string FirstLetterToUpperCaseOrConvertNullToEmptyString(this string s)
{
if (string.IsNullOrEmpty(s))
return string.Empty;
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
注意:使用ToCharArray比替代char.ToUpper(s[0]) + s.Substring(1)更快的原因是只分配了一个字符串,而Substring方法为子字符串分配了一个字符串,然后再分配一个字符串来组成最终结果。
下面是这种方法的样子,结合CarlosMuñoz接受的答案的初始测试:
/// <summary>
/// Returns the input string with the first character converted to uppercase
/// </summary>
public static string FirstLetterToUpperCase(this string s)
{
if (string.IsNullOrEmpty(s))
throw new ArgumentException("There is no first letter");
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}