![](/img/trans.png)
[英]C# utility class for to make the first letter upper case and trim an input string
[英]Make first letter of a string upper case (with maximum performance)
我有一個帶有TextBox
的DetailsView
,我希望輸入數據始終以大寫的第一個字母保存。
例子:
"red" --> "Red"
"red house" --> " Red house"
我怎樣才能實現這種最大化的性能?
注意:
根據答案和答案下的評論,許多人認為這是在詢問是否將字符串中的所有單詞大寫。 例如=> Red House
不是,但如果這是您所尋求的,請尋找使用TextInfo
的ToTitleCase
方法的答案之一。 (注意:對於實際提出的問題,這些答案是不正確的。)請參閱TextInfo.ToTitleCase 文檔以了解警告(不涉及全大寫單詞 - 它們被視為首字母縮略詞;可能在“不應該”的單詞中間出現小寫字母降低,例如,“McDonald”→“Mcdonald”;不保證能處理所有文化特定的細微差別重新大寫規則。)
注意:
關於第一個之后的字母是否應該強制小寫的問題是模棱兩可的。 接受的答案假定只有第一個字母應該改變。 如果您想強制字符串中除第一個之外的所有字母為小寫,請查找包含ToLower
且不包含 ToTitleCase的答案。
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>
,如果我們使用.ToSpan(1)
而不是.Substring(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)),
_ => input[0].ToString().ToUpper() + input.Substring(1)
};
}
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's answer 。
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
有效值。
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());
}
正確的方法是使用文化:
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower())
注意:這將使字符串中的每個單詞大寫,例如“red house” --> “Red House”。 該解決方案還將單詞中的小寫字母大寫,例如“old McDonald” --> “Old Mcdonald”。
我從C# Uppercase First Letter - Dot Net Perls 中采用了最快的方法並轉換為擴展方法:
/// <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);
}
您可以使用“ToTitleCase 方法”:
string s = new CultureInfo("en-US").TextInfo.ToTitleCase("red house");
//result : Red House
這種擴展方法解決了每個標題問題。
這個用起來很簡單:
string str = "red house";
str.ToTitleCase();
//result : Red house
string 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 latter
public 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
}
}
對於第一個字母,帶有錯誤檢查:
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);
}
public static string ToInvarianTitleCase(this string self)
{
if (string.IsNullOrWhiteSpace(self))
{
return self;
}
return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(self);
}
使用string.Create()並避免在我們的方法中使用throw
關鍵字(是的,您沒看錯),我們可以更進一步地使用Marcell 的答案。 此外,我的方法處理任意長度的字符串(例如,幾兆字節的文本)。
public static string L33t(this string s)
{
static void ThrowError() => throw new ArgumentException("There is no first letter");
if (string.IsNullOrEmpty(s))
ThrowError(); // No "throw" keyword to avoid costly IL
return string.Create(s.Length, s, (chars, state) =>
{
state.AsSpan().CopyTo(chars); // No slicing to save some CPU cycles
chars[0] = char.ToUpper(chars[0]);
});
}
以下是在.NET Core 3.1.7, 64 位上運行的基准測試的數字。 我添加了一個更長的字符串來確定額外副本的成本。
方法 | 數據 | 意思 | 錯誤 | 標准差 | 中位數 |
---|---|---|---|---|---|
L33t | 紅色的 | 8.545 納秒 | 0.4612 納秒 | 1.3308 納秒 | 8.075 納秒 |
馬塞爾 | 紅色的 | 9.153 納秒 | 0.3377 納秒 | 0.9471 納秒 | 8.946 納秒 |
L33t | 紅房子 | 7.715 納秒 | 0.1741 納秒 | 0.4618 納秒 | 7.793 納秒 |
馬塞爾 | 紅房子 | 10.537 納秒 | 0.5002 納秒 | 1.4351 納秒 | 10.377 納秒 |
L33t | 紅色 r(...)house [89] | 11.121 納秒 | 0.6774 納秒 | 1.9106 納秒 | 10.612 納秒 |
馬塞爾 | 紅色 r(...)house [89] | 16.739 納秒 | 0.4468 納秒 | 1.3033 納秒 | 16.853 納秒 |
using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace CorePerformanceTest
{
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<StringUpperTest>();
}
}
public class StringUpperTest
{
[Params("red", "red house", "red red red red red red red red red red red red red red red red red red red red red house")]
public string Data;
[Benchmark]
public string Marcell() => Data.Marcell();
[Benchmark]
public string L33t() => Data.L33t();
}
internal static class StringExtensions
{
public static string Marcell(this string s)
{
if (string.IsNullOrEmpty(s))
throw new ArgumentException("There is no first letter");
Span<char> a = stackalloc char[s.Length];
s.AsSpan(1).CopyTo(a.Slice(1));
a[0] = char.ToUpper(s[0]);
return new string(a);
}
public static string L33t(this string s)
{
static void ThrowError() => throw new ArgumentException("There is no first letter");
if (string.IsNullOrEmpty(s))
ThrowError(); // IMPORTANT: Do not "throw" here!
return string.Create(s.Length, s, (chars, state) =>
{
state.AsSpan().CopyTo(chars);
chars[0] = char.ToUpper(chars[0]);
});
}
}
}
請讓我知道你是否可以讓它更快!
最快的方法:
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);
}
測試顯示下一個結果(輸入為 1,0000,000 個符號的字符串):
由於這個問題是關於最大化性能,我采用了Darren 的版本,使用Span
s,減少了垃圾並提高了大約 10% 的速度。
/// <summary>
/// Returns the input string with the first character converted to uppercase
/// </summary>
public static string ToUpperFirst(this string s)
{
if (string.IsNullOrEmpty(s))
throw new ArgumentException("There is no first letter");
Span<char> a = stackalloc char[s.Length];
s.AsSpan(1).CopyTo(a.Slice(1));
a[0] = char.ToUpper(s[0]);
return new string(a);
}
方法 | 數據 | 意思 | 錯誤 | 標准差 |
---|---|---|---|---|
卡洛斯 | 紅色的 | 107.29 納秒 | 2.2401 納秒 | 3.9234 納秒 |
達倫 | 紅色的 | 30.93 納秒 | 0.9228 納秒 | 0.8632 納秒 |
馬塞爾 | 紅色的 | 26.99 納秒 | 0.3902 納秒 | 0.3459 納秒 |
卡洛斯 | 紅房子 | 106.78 納秒 | 1.9713 納秒 | 1.8439 納秒 |
達倫 | 紅房子 | 32.49 納秒 | 0.4253 納秒 | 0.3978 納秒 |
馬塞爾 | 紅房子 | 27.37 納秒 | 0.3888 納秒 | 0.3637 納秒 |
using System;
using System.Linq;
using BenchmarkDotNet.Attributes;
namespace CorePerformanceTest
{
public class StringUpperTest
{
[Params("red", "red house")]
public string Data;
[Benchmark]
public string Carlos() => Data.Carlos();
[Benchmark]
public string Darren() => Data.Darren();
[Benchmark]
public string Marcell() => Data.Marcell();
}
internal static class StringExtensions
{
public static string Carlos(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)
};
public static string Darren(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);
}
public static string Marcell(this string s)
{
if (string.IsNullOrEmpty(s))
throw new ArgumentException("There is no first letter");
Span<char> a = stackalloc char[s.Length];
s.AsSpan(1).CopyTo(a.Slice(1));
a[0] = char.ToUpper(s[0]);
return new string(a);
}
}
}
如果性能/內存使用是一個問題,那么這個只會創建一 (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;
}
嘗試這個:
static public string UpperCaseFirstCharacter(this string text) {
return Regex.Replace(text, "^[a-z]", m => m.Value.ToUpper());
}
由於我碰巧也在做這方面的工作,並且正在四處尋找任何想法,這就是我找到的解決方案。 它使用 LINQ,並且能夠將字符串的第一個字母大寫,即使第一次出現的不是字母。 這是我最終制作的擴展方法。
public static string CaptalizeFirstLetter(this string data)
{
var chars = data.ToCharArray();
// Find the Index of the first letter
var charac = data.First(char.IsLetter);
var i = data.IndexOf(charac);
// capitalize that letter
chars[i] = char.ToUpper(chars[i]);
return new string(chars);
}
我相信有一種方法可以稍微優化或清理它。
如果您只關心第一個字母是否大寫而字符串的其余部分無關緊要,則只需選擇第一個字符,將其設為大寫,然后將其與沒有原始第一個字符的字符串的其余部分連接起來。
String word ="red house";
word = word[0].ToString().ToUpper() + word.Substring(1, word.length -1);
//result: word = "Red house"
我們需要將第一個字符轉成ToString(),因為我們是把它讀成一個Char數組,而Char類型沒有ToUpper()方法。
檢查字符串是否不為空,將第一個字符轉換為大寫,其余字符轉換為小寫:
public static string FirstCharToUpper(string str)
{
return str?.First().ToString().ToUpper() + str?.Substring(1).ToLower();
}
這是一種將其作為擴展方法的方法:
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);
}
我在C# 大寫首字母 - Dot Net Perls 中找到了一些東西:
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);
}
這將做到這一點,盡管它還將確保沒有不在單詞開頭的錯誤大寫。
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);
}
當您只需要以下內容時,這里似乎有很多復雜性:
/// <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);
}
值得注意的點:
這是一種擴展方法。
如果輸入為空、空白或空白,則按原樣返回輸入。
String.IsNullOrWhiteSpace是在 .NET Framework 4 中引入的。這不適用於舊框架。
我想提供一個“最大性能”的答案。 在我看來, “最大性能”的答案涵蓋了所有場景,並為這些場景的問題提供了答案。 所以,這是我的答案。 由於這些原因:
IsNullOrWhiteSpace 說明只有空格或空/空的字符串。
.Trim() 從字符串的前面和后面刪除空白。
.First() 獲取 IEnumerable<TSource>(或字符串)的第一個元素。
我們應該檢查它是否是一個可以/應該是大寫的字母。
然后我們添加字符串的其余部分,只有當長度表明我們應該這樣做時。
根據 .NET 最佳實踐,我們應該在 System.Globalization.CultureInfo 下提供一種文化。
將它們提供為可選參數使此方法完全可重用,而不必每次都鍵入所選的文化。
我還注意到我的和大多數這些答案都沒有保留字符串開頭的空格。 這還將展示如何維護該空白。
//Capitalize the first letter disregard all chars using regex. public static string RegCapString(this string instring, string culture = "en-US", bool useSystem = false) { if (string.IsNullOrWhiteSpace(instring)) { return instring; } var m = Regex.Match(instring, "[A-Za-z]").Index; return instring.Substring(0, m) + instring[m].ToString().ToUpper(new CultureInfo(culture, useSystem)) + instring.Substring(m + 1); } //Capitalize first char if it is a letter disregard white space. public static string CapString(this string instring, string culture = "en-US", bool useSystem = false) { if (string.IsNullOrWhiteSpace(instring) || !char.IsLetter(instring.Trim().First())) { return instring; } var whiteSpaces = instring.Length - instring.TrimStart().Length; return (new string(' ', whiteSpaces)) + instring.Trim().First().ToString().ToUpper(new CultureInfo(culture, useSystem)) + ((instring.TrimStart().Length > 1) ? instring.Substring(whiteSpaces + 1) : ""); }
我認為下面的方法是最好的解決方案。
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));
}
}
Output
Something In The Way
Dot Net PERLS
String_two;three
Sam
解決您的問題的可能解決方案:
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();
}
string emp="TENDULKAR";
string output;
output=emp.First().ToString().ToUpper() + String.Join("", emp.Skip(1)).ToLower();
我有一個帶TextBox
的DetailsView
,並且我希望輸入數據總是始終用首字母大寫保存。
例子:
"red" --> "Red"
"red house" --> " Red house"
我如何才能實現這種最大化的性能?
注意:
基於答案和答案下的注釋,許多人認為這是在問是否將字符串中的所有單詞都大寫。 例如=> Red House
不是,但是如果您要尋找的是,請尋找使用TextInfo
的ToTitleCase
方法的答案之一。 (注意:這些答案對於實際提出的問題是不正確的。)
注意事項,請參見TextInfo.ToTitleCase doc (不要觸摸全大寫單詞-它們被視為首字母縮寫詞;可以將“不應”降低的單詞中間的小寫字母,例如“ McDonald” =>“ Mcdonald”;不保證處理所有特定於文化的細微內容重新大寫的規則。)
注意:
關於是否應將首字母后的字母強制小寫,這個問題尚不明確。 可接受的答案假定只應更改第一個字母。 如果要強制字符串中除第一個字母外的所有字母都為小寫字母,請查找包含ToLower
而不包含ToTitleCase的答案。
似乎這里給出的解決方案都不會處理字符串前的空格。
只是添加這個作為一個想法:
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
))。
FluentSharp 具有執行此操作的lowerCaseFirstLetter
方法。
這是最快的方法:
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;
}
將首字母大寫的最簡單方法是:
1-使用Sytem.Globalization;
// Creates a TextInfo based on the "en-US" culture.
TextInfo myTI = new CultureInfo("en-US",false).
myTI.ToTitleCase(textboxname.Text)
`
我有一個帶TextBox
的DetailsView
,並且我希望輸入數據總是始終用首字母大寫保存。
例子:
"red" --> "Red"
"red house" --> " Red house"
我如何才能實現這種最大化的性能?
注意:
基於答案和答案下的注釋,許多人認為這是在問是否將字符串中的所有單詞都大寫。 例如=> Red House
不是,但是如果您要尋找的是,請尋找使用TextInfo
的ToTitleCase
方法的答案之一。 (注意:這些答案對於實際提出的問題是不正確的。)
注意事項,請參見TextInfo.ToTitleCase doc (不要觸摸全大寫單詞-它們被視為首字母縮寫詞;可以將“不應”降低的單詞中間的小寫字母,例如“ McDonald” =>“ Mcdonald”;不保證處理所有特定於文化的細微內容重新大寫的規則。)
注意:
關於是否應將首字母后的字母強制小寫,這個問題尚不明確。 可接受的答案假定只應更改第一個字母。 如果要強制字符串中除第一個字母外的所有字母都為小寫字母,請查找包含ToLower
而不包含ToTitleCase的答案。
以下功能適用於所有方式:
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);
}
擴展上面 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;
}
我有一個帶TextBox
的DetailsView
,並且我希望輸入數據總是始終用首字母大寫保存。
例子:
"red" --> "Red"
"red house" --> " Red house"
我如何才能實現這種最大化的性能?
注意:
基於答案和答案下的注釋,許多人認為這是在問是否將字符串中的所有單詞都大寫。 例如=> Red House
不是,但是如果您要尋找的是,請尋找使用TextInfo
的ToTitleCase
方法的答案之一。 (注意:這些答案對於實際提出的問題是不正確的。)
注意事項,請參見TextInfo.ToTitleCase doc (不要觸摸全大寫單詞-它們被視為首字母縮寫詞;可以將“不應”降低的單詞中間的小寫字母,例如“ McDonald” =>“ Mcdonald”;不保證處理所有特定於文化的細微內容重新大寫的規則。)
注意:
關於是否應將首字母后的字母強制小寫,這個問題尚不明確。 可接受的答案假定只應更改第一個字母。 如果要強制字符串中除第一個字母外的所有字母都為小寫字母,請查找包含ToLower
而不包含ToTitleCase的答案。
我們可以這樣做(C# 8.0、.NET 5):
input?.Length > 0 ? char.ToUpperInvariant(input[0]) + input[1..] : input
我相信這足夠短,可以進行內聯。
如果input
是一個空字符串,我們得到一個空字符串。 如果input
為null
,我們得到null
。
否則,代碼采用第一個字符input[0]
並使用char.ToUpperInvariant
將其轉換為大寫。 並連接其余的input[1..]
。
編譯器會將范圍訪問轉換為對Substring
的調用,而且它可以利用我們已經獲得長度的事實。
在接受的答案中,這具有不使用LINQ的優點。 其他一些答案將字符串轉換為數組只是為了取第一個字符。 這段代碼也沒有這樣做。
如果您更喜歡擴展方法,可以這樣做:
public static string FirstCharToUpper(this string input) =>
input?.Length > 0 ? char.ToUpperInvariant(input[0]) + input[1..] : input;
如果你更喜歡扔怎么辦? 好的,讓它拋出:
public static string FirstCharToUpper(this string input) =>
input switch
{
null => throw new ArgumentNullException(nameof(input)),
_ => input.Length > 0 ? char.ToUpperInvariant(input[0]) + input[1..] : input
};
這里大致等效的代碼(因為我們正在制作一個擴展方法,我們可以更詳細一點):
public static string FirstCharToUpperEquivalent(this string input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
var length = input.Length;
if (length == 0)
{
return input;
}
string firstCharacter = char.ToUpperInvariant(input[0]).ToString();
return string.Concat(firstCharacter, input.Substring(1, length - 1));
}
我用 1000 輪 155 個單詞做了一個基准測試(所以它們被調用了 155000 次),這是結果:
Benchmarking type Tests
TestAccepted 00:00:00.0465979
TestProposalNoThrow 00:00:00.0092839
TestProposalDoThrow 00:00:00.0092938
TestProposalEquival 00:00:00.0091463
我在 Windows 10、Intel Core i3上運行它,使用來自 Jon Skeet 的Simple microbenchmarking in C#的代碼。
這是對我有用的代碼:
private string StringLetterUppercase(string input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
else if (input == "")
{
throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input));
}
else
{
return input.First().ToString().ToUpper() + input.Substring(1);
}
}
使用這種方法,您可以高出每個單詞的第一個字符。
示例“ 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)));
}
發送一個字符串到這個函數。 它會首先檢查字符串是空還是空,如果不是字符串將是所有較低的字符。 然后返回字符串上面的其余部分的第一個字符。
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);
}
這也適用,使用 Take、Skip 和 Aggregate:
public static string FirstCharToUpper(this string text)
{
if (String.IsNullOrEmpty(text)) return String.Empty;
var first = text.Take(1).ToArray()[0].ToString().ToUpper();
var rest = text.Skip(1).Aggregate("", ((xs, x) => xs + x));
return first + rest;
}
正如 BobBeechey 在他對這個問題的回答中所建議的那樣,以下代碼將適用於此:
private void txt_fname_TextChanged(object sender, EventArgs e)
{
char[] c = txt_fname.Text.ToCharArray();
int j;
for (j = 0; j < txt_fname.Text.Length; j++)
{
if (j==0) c[j]=c[j].ToString().ToUpper()[0];
else c[j] = c[j].ToString().ToLower()[0];
}
txt_fname.Text = new string(c);
txt_fname.Select(txt_fname.Text.Length, 1);
}
string input = "red HOUSE";
System.Text.StringBuilder sb = new System.Text.StringBuilder(input);
for (int j = 0; j < sb.Length; j++)
{
if ( j == 0 ) //catches just the first letter
sb[j] = System.Char.ToUpper(sb[j]);
else //everything else is lower case
sb[j] = System.Char.ToLower(sb[j]);
}
// Store the new string.
string corrected = sb.ToString();
System.Console.WriteLine(corrected);
我用它來更正名稱。 如果字符遵循特定模式,它基本上適用於將字符更改為大寫的概念。 在這種情況下,我已經去了空間和“Mc”的破折號。
private String CorrectName(String name)
{
List<String> StringsToCapitalizeAfter = new List<String>() { " ", "-", "Mc" };
StringBuilder NameBuilder = new StringBuilder();
name.Select(c => c.ToString()).ToList().ForEach(c =>
{
c = c.ToLower();
StringsToCapitalizeAfter.ForEach(s =>
{
if(String.IsNullOrEmpty(NameBuilder.ToString()) ||
NameBuilder.ToString().EndsWith(s))
{
c = c.ToUpper();
}
});
NameBuilder.Append(c);
});
return NameBuilder.ToString();
}
private string capitalizeFirstCharacter(string format)
{
if (string.IsNullOrEmpty(format))
return string.Empty;
else
return char.ToUpper(format[0]) + format.ToLower().Substring(1);
}
string s_Val = "test";
if (s_Val != "")
{
s_Val = char.ToUpper(s_Val[0]);
if (s_Val.Length > 1)
{
s_Val += s_Val.Substring(1);
}
}
最簡單和最快的方法是將字符串的第一個字符替換為大寫字符:
string str = "test";<br>
str = str.Replace(str[0], char.ToUpper(str[0]));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.