C# 使字符串的第一个字母大写(具有最大性能)
我有一个带有C# 使字符串的第一个字母大写(具有最大性能),c#,performance,C#,Performance,我有一个带有文本框的详细视图 我希望输入的数据总是用大写的第一个字母保存 示例: "red" --> "Red" "red house" --> " Red house" 我如何才能实现这一点,使性能最大化 注意: 根据答案和答案下的注释,许多人认为这是关于将字符串中的所有单词大写的问题。例如,=>redhouse它不是,但如果这是您所寻求的,请查找使用TextInfo的ToTitleCase方法的答案之一。(注意:这些答案对于实际提出的问题是不正确的。) 有关注意事项,请参阅(
文本框的详细视图
我希望输入的数据总是用大写的第一个字母保存
示例:
"red" --> "Red"
"red house" --> " Red house"
我如何才能实现这一点,使性能最大化
注意:
根据答案和答案下的注释,许多人认为这是关于将字符串中的所有单词大写的问题。例如,=>redhouse
它不是,但如果这是您所寻求的,请查找使用TextInfo
的ToTitleCase
方法的答案之一。(注意:这些答案对于实际提出的问题是不正确的。)
有关注意事项,请参阅(不涉及所有大写字母-它们被视为首字母缩写;单词中间的小写字母“不应该”被降下,例如“McDonald”=>“McDonald”;不保证处理所有特定于文化的微妙之处-重新大写规则。)
注意:
第一个字母后面的字母是否应该强制小写,这个问题是不明确的。被接受的答案假设只有第一个字母应该被修改。如果要强制字符串中除第一个字母外的所有字母为小写,请查找包含ToLower
,但不包含ToTitleCase的答案。对于第一个字母,请检查错误:
public string CapitalizeFirstLetter(string s)
{
if (String.IsNullOrEmpty(s))
return s;
if (s.Length == 1)
return s.ToUpper();
return s.Remove(1).ToUpper() + s.Substring(1);
}
这和一个方便的扩展一样
public static string CapitalizeFirstLetter(this string s)
{
if (String.IsNullOrEmpty(s)) return s;
if (s.Length == 1) return s.ToUpper();
return s.Remove(1).ToUpper() + s.Substring(1);
}
旧答案:
这使得每个第一个字母都是大写的
public string ToTitleCase(string str)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
这可以做到,尽管它也可以确保单词开头没有不正确的大写字母
public string(string s)
{
System.Globalization.CultureInfo c = new System.Globalization.CultureInfo("en-us", false)
System.Globalization.TextInfo t = c.TextInfo;
return t.ToTitleCase(s);
}
更新至C#8
C#7
非常古老的答案
编辑:
这个版本比较短。要获得更快的解决方案,请查看
编辑2:
可能最快的解决方案是(甚至有一个基准测试),尽管我会将它的string.IsNullOrEmpty更改为抛出异常,因为最初的需求要求存在第一个字母,所以它可以大写。请注意,此代码适用于通用字符串,而不是特别适用于文本框中的有效值
static public string UpperCaseFirstCharacter(this string text)
{
if (!string.IsNullOrEmpty(text))
{
return string.Format(
"{0}{1}",
text.Substring(0, 1).ToUpper(),
text.Substring(1));
}
return text;
}
/// <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);
}
然后可以这样称呼它:
//yields "This is Brian's test.":
"this is Brian's test.".UpperCaseFirstCharacter();
下面是一些针对它的单元测试:
[Test]
public void UpperCaseFirstCharacter_ZeroLength_ReturnsOriginal()
{
string orig = "";
string result = orig.UpperCaseFirstCharacter();
Assert.AreEqual(orig, result);
}
[Test]
public void UpperCaseFirstCharacter_SingleCharacter_ReturnsCapital()
{
string orig = "c";
string result = orig.UpperCaseFirstCharacter();
Assert.AreEqual("C", result);
}
[Test]
public void UpperCaseFirstCharacter_StandardInput_CapitalizeOnlyFirstLetter()
{
string orig = "this is Brian's test.";
string result = orig.UpperCaseFirstCharacter();
Assert.AreEqual("This is Brian's test.", result);
}
试试这个:
static public string UpperCaseFirstCharacter(this string text) {
return Regex.Replace(text, "^[a-z]", m => m.Value.ToUpper());
}
如果性能/内存使用是一个问题,那么这个问题只会创建一(1)个StringBuilder和一(1)个与原始字符串大小相同的新字符串
public static string ToUpperFirst(this string str) {
if( !string.IsNullOrEmpty( str ) ) {
StringBuilder sb = new StringBuilder(str);
sb[0] = char.ToUpper(sb[0]);
return sb.ToString();
} else return str;
}
您可以使用“ToTitleCase方法”
这种扩展方法解决了每一个滴定酶问题
易于使用
string str = "red house";
str.ToTitleCase();
//result : Red house
string str = "red house";
str.ToTitleCase(TitleCase.All);
//result : Red House
扩展法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace Test
{
public static class StringHelper
{
private static CultureInfo ci = new CultureInfo("en-US");
//Convert all first latter
public static string ToTitleCase(this string str)
{
str = str.ToLower();
var strArray = str.Split(' ');
if (strArray.Length > 1)
{
strArray[0] = ci.TextInfo.ToTitleCase(strArray[0]);
return string.Join(" ", strArray);
}
return ci.TextInfo.ToTitleCase(str);
}
public static string ToTitleCase(this string str, TitleCase tcase)
{
str = str.ToLower();
switch (tcase)
{
case TitleCase.First:
var strArray = str.Split(' ');
if (strArray.Length > 1)
{
strArray[0] = ci.TextInfo.ToTitleCase(strArray[0]);
return string.Join(" ", strArray);
}
break;
case TitleCase.All:
return ci.TextInfo.ToTitleCase(str);
default:
break;
}
return ci.TextInfo.ToTitleCase(str);
}
}
public enum TitleCase
{
First,
All
}
}
因为我碰巧也在做这件事,并且四处寻找任何想法,这就是我找到的解决方案。它使用LINQ,并且能够大写字符串的第一个字母,即使第一次出现的不是字母。这是我最后制作的扩展方法
public static string CaptalizeFirstLetter(this string data)
{
var chars = data.ToCharArray();
// Find the Index of the first letter
var charac = data.First(char.IsLetter);
var i = data.IndexOf(charac);
// capitalize that letter
chars[i] = char.ToUpper(chars[i]);
return new string(chars);
}
我相信有一种方法可以稍微优化或清理它。我在这里发现了一些东西:
public static string ToInvarianTitleCase(this string self)
{
if (string.IsNullOrWhiteSpace(self))
{
return self;
}
return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(self);
}
也许这有帮助 这里给出的解决方案似乎都不会处理字符串前的空白
我只是想补充一下:
public static string SetFirstCharUpper2(string aValue, bool aIgonreLeadingSpaces = true)
{
if (string.IsNullOrWhiteSpace(aValue))
return aValue;
string trimmed = aIgonreLeadingSpaces
? aValue.TrimStart()
: aValue;
return char.ToUpper(trimmed[0]) + trimmed.Substring(1);
}
它应该处理这对其他答案不起作用(该句开头有空格),如果您不喜欢空格修剪,只需传递false
作为第二个参数(或者将默认值更改为false
,如果要处理空格,则传递true
)当您需要的只是:
/// <summary>
/// Returns the input string with the first character converted to uppercase if a letter
/// </summary>
/// <remarks>Null input returns null</remarks>
public static string FirstLetterToUpperCase(this string s)
{
if (string.IsNullOrWhiteSpace(s))
return s;
return char.ToUpper(s[0]) + s.Substring(1);
}
//
///返回第一个字符转换为大写的输入字符串(如果为字母)
///
///Null输入返回Null
公共静态字符串FirstLetterToUpperCase(此字符串为s)
{
if(string.IsNullOrWhiteSpace)
返回s;
返回字符ToUpper(s[0])+s子字符串(1);
}
值得注意的是:
这是一种扩展方法
如果输入为null、空或空白,则按原样返回输入
是在.NET Framework 4中引入的。这不适用于较旧的框架
我采用了最快的方法,并将其转换为扩展方法:
static public string UpperCaseFirstCharacter(this string text)
{
if (!string.IsNullOrEmpty(text))
{
return string.Format(
"{0}{1}",
text.Substring(0, 1).ToUpper(),
text.Substring(1));
}
return text;
}
/// <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);
}
FluentSharp具有执行此操作的lowerCaseFirstLetter
方法
这是最快的方式:
public static unsafe void ToUpperFirst(this string str)
{
if (str == null) return;
fixed (char* ptr = str)
*ptr = char.ToUpper(*ptr);
}
在不更改原始字符串的情况下:
public static unsafe string ToUpperFirst(this string str)
{
if (str == null) return null;
string ret = string.Copy(str);
fixed (char* ptr = ret)
*ptr = char.ToUpper(*ptr);
return ret;
}
如果您只关心首字母大写,而与字符串的其余部分无关,则只需选择第一个字符,使其大写,并将其与字符串的其余部分连接,而不使用原始的第一个字符
String word ="red house";
word = word[0].ToString().ToUpper() + word.Substring(1, word.length -1);
//result: word = "Red house"
我们需要将第一个字符转换为字符串(),因为我们将其作为字符数组读取,而字符类型没有ToUpper()方法。最快的方法
private string Capitalize(string s){
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
测试显示下一个结果(输入10000000个符号的字符串):
正确的方法是使用文化:
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower())
注意:这将大写字符串中的每个单词,例如“red house”->“red house”。该解决方案还将大写字母小写,例如“old McDonald”->“old McDonald”。以下函数适用于所有方面:
static string UppercaseWords(string value)
{
char[] array = value.ToCharArray();
// Handle the first letter in the string.
if (array.Length >= 1)
{
if (char.IsLower(array[0]))
{
array[0] = char.ToUpper(array[0]);
}
}
// Scan through the letters, checking for spaces.
// ... Uppercase the lowercase letters following spaces.
for (int i = 1; i < array.Length; i++)
{
if (array[i - 1] == ' ')
{
if (char.IsLower(array[i]))
{
array[i] = char.ToUpper(array[i]);
}
}
}
return new string(array);
}
静态字符串大写字(字符串值)
{
char[]数组=value.ToCharArray();
//处理字符串中的第一个字母。
如果(array.Length>=1)
{
if(char.IsLower(数组[0]))
{
数组[0]=char.ToUpper(数组[0]);
}
}
//浏览字母,检查空格。
//…大写字母空格后的小写字母。
for(int i=1;i
我发现扩展了卡洛斯的问题,如果你想资本化的话
/// <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);
}
public static unsafe void ToUpperFirst(this string str)
{
if (str == null) return;
fixed (char* ptr = str)
*ptr = char.ToUpper(*ptr);
}
public static unsafe string ToUpperFirst(this string str)
{
if (str == null) return null;
string ret = string.Copy(str);
fixed (char* ptr = ret)
*ptr = char.ToUpper(*ptr);
return ret;
}
String word ="red house";
word = word[0].ToString().ToUpper() + word.Substring(1, word.length -1);
//result: word = "Red house"
private string Capitalize(string s){
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower())
static string UppercaseWords(string value)
{
char[] array = value.ToCharArray();
// Handle the first letter in the string.
if (array.Length >= 1)
{
if (char.IsLower(array[0]))
{
array[0] = char.ToUpper(array[0]);
}
}
// Scan through the letters, checking for spaces.
// ... Uppercase the lowercase letters following spaces.
for (int i = 1; i < array.Length; i++)
{
if (array[i - 1] == ' ')
{
if (char.IsLower(array[i]))
{
array[i] = char.ToUpper(array[i]);
}
}
}
return new string(array);
}
/// <summary>
/// Capitalize first letter of every sentence.
/// </summary>
/// <param name="inputSting"></param>
/// <returns></returns>
public string CapitalizeSentences (string inputSting)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(inputSting))
{
string[] sentences = inputSting.Split('.');
foreach (string sentence in sentences)
{
result += string.Format ("{0}{1}.", sentence.First().ToString().ToUpper(), sentence.Substring(1));
}
}
return result;
}
public static string capString(string instring, string culture = "en-US", bool useSystem = false)
{
string outstring;
if (String.IsNullOrWhiteSpace(instring))
{
return "";
}
instring = instring.Trim();
char thisletter = instring.First();
if (!char.IsLetter(thisletter))
{
return instring;
}
outstring = thisletter.ToString().ToUpper(new CultureInfo(culture, useSystem));
if (instring.Length > 1)
{
outstring += instring.Substring(1);
}
return outstring;
}
string input;
string output;
input = "red house";
output = String.Concat(input.Select((currentChar, index) => index == 0 ? Char.ToUpper(currentChar) : currentChar));
//output = "Red house"
public static class StringExtensions
{
public static string FirstLetterToUpper(this string input)
{
if (string.IsNullOrEmpty(input))
return string.Empty;
return String.Concat(input.Select((currentChar, index) => index == 0 ? Char.ToUpper(currentChar) : currentChar));
}
}
class Program
{
static string UppercaseWords(string value)
{
char[] array = value.ToCharArray();
// Handle the first letter in the string.
if (array.Length >= 1)
{
if (char.IsLower(array[0]))
{
array[0] = char.ToUpper(array[0]);
}
}
// Scan through the letters, checking for spaces.
// ... Uppercase the lowercase letters following spaces.
for (int i = 1; i < array.Length; i++)
{
if (array[i - 1] == ' ')
{
if (char.IsLower(array[i]))
{
array[i] = char.ToUpper(array[i]);
}
}
}
return new string(array);
}
static void Main()
{
// Uppercase words in these strings.
const string value1 = "something in the way";
const string value2 = "dot net PERLS";
const string value3 = "String_two;three";
const string value4 = " sam";
// ... Compute the uppercase strings.
Console.WriteLine(UppercaseWords(value1));
Console.WriteLine(UppercaseWords(value2));
Console.WriteLine(UppercaseWords(value3));
Console.WriteLine(UppercaseWords(value4));
}
}
Output
Something In The Way
Dot Net PERLS
String_two;three
Sam
public static string FirstCharToUpper(string str)
{
return str?.First().ToString().ToUpper() + str?.Substring(1).ToLower();
}
public static string FirstToUpper(this string lowerWord)
{
if (string.IsNullOrWhiteSpace(lowerWord) || string.IsNullOrEmpty(lowerWord))
return lowerWord;
return new StringBuilder(lowerWord.Substring(0, 1).ToUpper())
.Append(lowerWord.Substring(1))
.ToString();
}
| Method | Data | Mean | Error | StdDev |
|-------- |---------- |----------:|----------:|----------:|
| Carlos | red | 107.29 ns | 2.2401 ns | 3.9234 ns |
| Darren | red | 30.93 ns | 0.9228 ns | 0.8632 ns |
| Marcell | red | 26.99 ns | 0.3902 ns | 0.3459 ns |
| Carlos | red house | 106.78 ns | 1.9713 ns | 1.8439 ns |
| Darren | red house | 32.49 ns | 0.4253 ns | 0.3978 ns |
| Marcell | red house | 27.37 ns | 0.3888 ns | 0.3637 ns |
using System;
using System.Linq;
using BenchmarkDotNet.Attributes;
namespace CorePerformanceTest
{
public class StringUpperTest
{
[Params("red", "red house")]
public string Data;
[Benchmark]
public string Carlos() => Data.Carlos();
[Benchmark]
public string Darren() => Data.Darren();
[Benchmark]
public string Marcell() => Data.Marcell();
}
internal static class StringExtensions
{
public static string Carlos(this string input) =>
input switch
{
null => throw new ArgumentNullException(nameof(input)),
"" => throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input)),
_ => input.First().ToString().ToUpper() + input.Substring(1)
};
public static string Darren(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);
}
public static string Marcell(this string s)
{
if (string.IsNullOrEmpty(s))
throw new ArgumentException("There is no first letter");
Span<char> a = stackalloc char[s.Length];
s.AsSpan(1).CopyTo(a.Slice(1));
a[0] = char.ToUpper(s[0]);
return new string(a);
}
}
}