更新到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.First().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.First().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));}编辑
:此版本较短。为了获得更快的解决方案,请看一下Equiso的答案
public static string FirstCharToUpper(string input){ if (String.IsNullOrEmpty(input)) throw new ArgumentException("ARGH!"); return input.First().ToString().ToUpper() + input.Substring(1);}编辑2 :最快的解决方案可能是达伦的解决方案(甚至有一个基准),尽管我会更改它的
string.IsNullOrEmpty(s)验证以引发异常,因为最初的要求要求存在第一个字母,以便可以将其大写。请注意,此代码适用于通用字符串,而不适用于的有效值
Textbox。



