不同C#版本的解决方案
C# 8与至少.NET Core 3.0或.NET Standard 2.1
public static class StringExtensions
{
public static string FirstCharToUpper(this string input) =>
input switch
{
null => throw new ArgumentNullException(nameof(input)),
"" => throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input)),
_ => string.Concat(input[0].ToString().ToUpper(), input.AsSpan(1))
};
}
自 .NET Core 3.0 / .NET Standard 2.1 开始,String.Concat()
支持 ReadonlySpan<char>
。如果我们使用 .AsSpan(1)
而不是 .Substring(1)
,可以节省一个内存分配。
C# 8
public static class StringExtensions
{
public static string FirstCharToUpper(this string input) =>
input switch
{
null => throw new ArgumentNullException(nameof(input)),
"" => throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input)),
_ => input[0].ToString().ToUpper() + input.Substring(1)
};
}
C# 7
public static class StringExtensions
{
public static string FirstCharToUpper(this string input)
{
switch (input)
{
case null: throw new ArgumentNullException(nameof(input));
case "": throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input));
default: return input[0].ToString().ToUpper() + input.Substring(1);
}
}
}
非常老的答案
public static string FirstCharToUpper(string input)
{
if (String.IsNullOrEmpty(input))
throw new ArgumentException("ARGH!");
return input.First().ToString().ToUpper() + String.Join("", input.Skip(1));
}
这个版本更短。如果想要更快的解决方案,请查看Diego的回答。
public static string FirstCharToUpper(string input)
{
if (String.IsNullOrEmpty(input))
throw new ArgumentException("ARGH!");
return input.First().ToString().ToUpper() + input.Substring(1);
}
可能最快的解决方法是Darren的(甚至有一个基准测试),尽管我会改变它的string.IsNullOrEmpty(s)
验证以抛出异常,因为原始要求期望首字母存在,以便可以将其大写。请注意,此代码适用于通用字符串,而不是特定于来自Textbox
的有效值。