栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使字符串的首字母大写(具有最佳性能)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使字符串的首字母大写(具有最佳性能)

更新到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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/576151.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号