使字符串的首字母大写(具有最佳性能)
我有一个带TextBox
的DetailsView
,并且我希望输入数据 总是始终用首字母大写保存 。
例:
"red" --> "Red"
"red house" --> " Red house"
我如何才能实现这种最大化的性能 ?
注意 :
基于答案和答案下的注释,许多人认为这是在问是否要大写字符串中的所有单词。 例如=> Red House
不是,但是如果您要寻找的是,请寻找使用TextInfo
的ToTitleCase
方法的答案之一。 (注意:这些答案对于实际提出的问题是不正确的。)
注意事项,请参见TextInfo.ToTitleCase doc (不要触摸全大写字母的单词-它们被视为首字母缩写词;可以将“不应”的单词中间的小写字母降低,例如“ McDonald” =>“ Mcdonald”;不保证来处理所有特定于文化的细微之处重新大写的规则。)
注意 :
关于是否应将首字母后的字母强制 小写,这个问题尚不明确 。 接受的答案假定只应更改第一个字母 。 如果要强制字符串中除第一个字母外的所有字母都为小写字母 ,请查找包含ToLower
而不包含ToTitleCase的答案 。
#1楼
这是将其作为扩展方法的一种方法:
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;
}
然后可以这样称呼:
//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);
}
#2楼
尝试这个:
static public string UpperCaseFirstCharacter(this string text) {return Regex.Replace(text, "^[a-z]", m => m.Value.ToUpper());
}
#3楼
如果性能/内存使用成为问题,那么此函数仅创建一(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;
}
#4楼
您可以使用“ ToTitleCase方法”
string s = new CultureInfo("en-US").TextInfo.ToTitleCase("red house");
//result : Red House
这种扩展方法可以解决所有标题问题。
易于使用
string str = "red house";
str.ToTitleCase();
//result : Red housestring 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 latterpublic 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}
}
#5楼
string emp="TENDULKAR";
string output;
output=emp.First().ToString().ToUpper() + String.Join("", emp.Skip(1)).ToLower();
#6楼
使用以下代码:
string strtest ="PRASHANT";
strtest.First().ToString().ToUpper() + strtest.Remove(0, 1).ToLower();
#7楼
使用这种方法,您可以高出每个单词的第一个字符。
示例“ Hello wOrld” =>“ Hello World”
public static string FirstCharToUpper(string input)
{if (String.IsNullOrEmpty(input))throw new ArgumentException("Error");return string.Join(" ", input.Split(' ').Select(d => d.First().ToString().ToUpper() + d.ToLower().Substring(1)));
}
#8楼
由于我碰巧也在从事此工作,并且一直在寻找任何想法,因此这就是我的解决方案。 它使用LINQ,并且即使首字母不是字母,也可以将首字母大写。 这是我最终制作的扩展方法。
public static string CaptalizeFirstLetter(this string data)
{var chars = data.ToCharArray();// Find the Index of the first lettervar charac = data.First(char.IsLetter);var i = data.IndexOf(charac);// capitalize that letterchars[i] = char.ToUpper(chars[i]);return new string(chars);
}
我敢肯定有一种方法可以对此进行优化或清理。
#9楼
public static string ToInvarianTitleCase(this string self)
{if (string.IsNullOrWhiteSpace(self)){return self;}return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(self);
}
#10楼
我在这里http://www.dotnetperls.com/uppercase-first-letter找到了一些东西:
static string UppercaseFirst(string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{return string.Empty;
}
// Return char and concat substring.
return char.ToUpper(s[0]) + s.Substring(1);
}
也许这有帮助!
#11楼
似乎这里给出的解决方案都不会在字符串之前处理空格。
只是将此添加为一个想法:
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);
}
它应该处理this won't work on other answers
(该句子的开头有一个空格),如果您不喜欢空格修剪,只需将false
作为第二个参数传递(或将默认值更改为false
,然后传递如果您想处理空间,则为true
)
#12楼
当您需要的是:时,这里似乎有很多复杂性:
/// <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,空白或空白,则按原样返回输入。
.NET Framework 4中引入了String.IsNullOrWhiteSpace。这不适用于较旧的框架。
#13楼
我从http://www.dotnetperls.com/uppercase-first-letter中采用了最快的方法,并转换为扩展方法:
/// <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);}
注意:使用ToCharArray
的原因比替代char.ToUpper(s[0]) + s.Substring(1)
,是因为只分配了一个字符串,而Substring
方法为Substring
分配了一个字符串,然后分配了一个字符串字符串组成最终结果。
编辑 :这是这种方法的外观,再加上CarlosMuñoz接受的初始测试的答案 :
/// <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);}
#14楼
发送一个字符串到这个函数。 它会首先检查字符串是空还是空,如果不是字符串将是所有较低的字符。 然后返回字符串上面的其余部分的第一个字符。
string FirstUpper(string s){// Check for empty string.if (string.IsNullOrEmpty(s)){return string.Empty;}s = s.ToLower();// Return char and concat substring.return char.ToUpper(s[0]) + s.Substring(1);}
#15楼
FluentSharp具有lowerCaseFirstLetter
方法,该方法可以执行此操作
https://github.com/o2platform/FluentSharp/blob/700dc35759db8e2164771a71f73a801aa9379074/FluentSharp.CoreLib/ExtensionMethods/System/String_ExtensionMethods.cs#L575
#16楼
最快的方法:
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;
}
#17楼
如果您只关心首字母大写,而字符串的其余部分无关紧要,则可以选择第一个字符,将其大写,然后将其与字符串的其余部分连接起来,而不使用原始的第一个字符。
String word ="red house";
word = word[0].ToString().ToUpper() + word.Substring(1, word.length -1);
//result: word = "Red house"
我们需要转换第一个字符ToString(),因为我们将其读取为Char数组,并且Char类型没有ToUpper()方法。
#18楼
将首字母大写的最简单方法是:
1-使用Sytem.Globalization;
// Creates a TextInfo based on the "en-US" culture.TextInfo myTI = new CultureInfo("en-US",false).myTI.ToTitleCase(textboxname.Text)
`
#19楼
最快的方法。
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符号的字符串): 测试结果
#20楼
正确的方法是使用文化:
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower())
注意:这将大写字符串中的每个单词,例如“ red house”->“ Red House”。 该解决方案还将在单词中使用小写大写,例如“ Old McDonald”->“ Old Mcdonald”。
#21楼
对于第一个字母,进行错误检查:
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);}
#22楼
public string FirstLetterToUpper(string str)
{if (str == null)return null;if (str.Length > 1)return char.ToUpper(str[0]) + str.Substring(1);return str.ToUpper();
}
旧答案:这会使每个首字母大写
public string ToTitleCase(string str)
{return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
#23楼
尽管可以做到这一点,但它也可以确保没有出现在单词开头的错误大写字母。
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);
}
#24楼
这会将第一个字母和每个字母大写,后跟一个空格,并将其他任何字母都小写。
public string CapitalizeFirstLetterAfterSpace(string input)
{System.Text.StringBuilder sb = new System.Text.StringBuilder(input);bool capitalizeNextLetter = true;for(int pos = 0; pos < sb.Length; pos++){if(capitalizeNextLetter){sb[pos]=System.Char.ToUpper(sb[pos]);capitalizeNextLetter = false;}else{sb[pos]=System.Char.ToLower(sb[pos]);}if(sb[pos]=' '){capitalizeNextLetter=true;}}
}
#25楼
以下功能在所有方面都是正确的:
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);
}
我发现在这里
#26楼
更新到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 :也许最快的解决方案是Darren's (甚至有一个基准),尽管我会更改它的string.IsNullOrEmpty(s)
验证会引发异常,因为原始要求要求存在第一个字母,因此可以将其大写。 请注意,此代码适用于通用字符串,而不适用于Textbox
有效值。
#27楼
扩展上面的Carlos问题,如果您想将多个句子都大写,可以使用以下代码:
/// <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; }
#28楼
我想提供一个“最大性能”的答案。 在我看来,“最大性能”答案涵盖了所有情况,并为解决这些情况的问题提供了答案。 所以,这是我的答案。 由于这些原因:
- IsNullOrWhiteSpace将字符串解释为只是空格或null / empty。
- .Trim()从字符串的前面和后面删除空格。
- .First()采用可枚举(或字符串)的第一个字符。
- 我们应该检查它是否可以/应该是大写字母。
- 然后,仅在长度指示应添加字符串时,才添加其余字符串。
- 通过.Net最佳实践,我们应该在System.Globalization.CultureInfo下提供一种文化。
将它们提供为可选参数使该方法完全可重用,而不必每次都键入所选区域性。
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; }
#29楼
最近,我有一个类似的要求,并记得LINQ函数Select()提供了一个索引:
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));}
}
请注意,只有第一个字母会转换为大写字母-其余所有字符都不会被触摸。 如果您需要其他字符为小写字母,则也可以为索引> 0调用Char.ToLower(currentChar)或首先对整个字符串调用ToLower()。
关于性能,我将代码与Darren的解决方案进行了比较。 在我的机器上,Darren的代码快了大约2倍,这并不奇怪,因为他仅直接编辑char数组中的第一个字母。 因此,如果需要最快的解决方案,我建议您使用Darren的代码。 如果您还希望集成其他字符串操作,那么让lambda函数的表达能力接触输入字符串的字符可能会很方便-您可以轻松扩展此函数-因此,我在此保留此解决方案。
#30楼
我认为以下方法是最好的解决方案
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));}
}OutputSomething In The Way
Dot Net PERLS
String_two;threeSam
参考
#31楼
检查字符串是否不为空,然后将第一个字符转换为大写,并将其余字符转换为小写:
public static string FirstCharToUpper(string str)
{return str?.First().ToString().ToUpper() + str?.Substring(1).ToLower();
}
#32楼
解决您的问题的可能解决方案。
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();}
使字符串的首字母大写(具有最佳性能)相关推荐
- mysql中首字母大写的函数,如何借助MySQL函数将字符串的首字母大写?
实际上,MySQL中没有单个函数仅将字符串的首字母大写.我们需要使用的功能,嵌套和针对这种情况,我们可以使用UPPER()和LOWER()使用SUBSTRING()方法.为了理解它,我们使用来自'em ...
- 根据汉字获取它的字符串拼音首字母(大写),含多音字
/// <summary> /// 根据汉字获取它的字符串拼音首字母(大写),含多音字 /// </summary> /// & ...
- 如何在JavaScript中将字符串的首字母大写?
如何使字符串的第一个字母大写,但不更改其他任何字母的大小写? 例如: "this is a test" -> "This is a test" " ...
- 如何将js字符串变成首字母大写其余小写
原文链接 一些大小写不规则的字符串,如"JAMES"."alice"."Amy"等,如何将他们统一的变成首字母大写其余小写的形式 首先是将字 ...
- mysql delette_关于字符串:首字母大写MySQL
用mysql的说法,有人知道这个tsql的等价物吗? 我正试图把每个条目的第一个字母大写. UPDATE tb_Company SET CompanyIndustry = UPPER(LEFT(Com ...
- 修改完 字符串单词首字母大写
/** * */ package excelOperation; /** * 该方法的主要作用是将EXCEL表中英文字符串的单词首字母转换为大写 */ import java.awt.Fram ...
- flash 与字符串:首字母大写
今天看到一个js的技巧感觉不错.记录一下.首字母变成大写.我们知道 toLocaleUpperCase 和 toLocaleLowerCase(), 都是改变大小写的. 这样你可以使用转换大小写的方法 ...
- 如何在JavaScript中大写字符串的首字母
To capitalize the first letter of a random string, you should follow these steps: 要大写随机字符串的第一个字母,应遵循 ...
- java 首字母大写方法
单个字符串需要进行首字母大写改写,网上大家的思路基本一致,就是将首字母截取,转化成大写然后再串上后面的,类似如下代码 //首字母大写 public static String firstLe ...
最新文章
- 面向对象之this与super
- k8s集群部署一(最新版docker安装)
- hdu 4725 The Shortest Path in Nya Graph(建图+优先队列dijstra)
- c++语言编辑简单的计算器,c++编写简单的计算器程序
- 树莓派进阶之路 (019) - 树莓派通过filezilla,samba与PC文件共享(转)
- 排序算法系列:插入排序算法
- CodeForces 1065E. Side Transmutations 计数
- python向lt新增5个元素_Python学习第十一课-MOOC嵩天
- java observable 使用_如何使用rxjava2取消Observable.timer?
- word无所不能之在word中浏览网页看电影
- 苹果mac专业音频处理软件:Audition
- 轻量级网络模型之EfficientNet
- android c 调用c,Android NDK 调用C
- mysql截取小数点后4位_MySQL 截取小数位数
- PMP澳门机考3A学员考试攻略
- 荣耀盒子无线网连接不上电脑连接服务器,华为荣耀盒子无法连接有线网络怎么解决...
- CSI笔记【9】:阵列信号处理及MATLAB实现(第2版)阅读随笔(一)
- 二次元风格好看的视频解析官网html源码
- 西安电子科技大学通院811电院821考研上岸经验分享(一)
- QQ空间无敌装逼,复制下面的任一代码粘贴即可出现意想不到的图案。
热门文章
- c++ 以模板类作为参数的模板
- 【Java源码分析】集合框架-Collections工具类-Arrays工具类
- Android-无障碍服务(AccessibilityService)
- java package作用_java import、package作用与用法
- python读取文件中的数据为二维数组变量_Numpy 多维数据数组的实现
- Android之如何优雅的管理ActionBar
- 【javascript基础】由demo来进阶学习闭包等概念
- Flutter开发之名篇及demo收录
- (0006) iOS 开发之JavaScriptCore 实现UIWebView和HTML的交互
- electron 剪贴板 截图_用electron开发了一个屏幕截图工具