不同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));
}
这个版本比较短。为了更快地解决问题,请看迭戈的回答。
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)验证来抛出异常,因为最初的需求期望第一个字母存在,以便它可以大写。注意,这段代码适用于一般字符串,而不是文本框中的有效值。