[英]How to capitalize the first character of each word, or the first character of a whole string, with C#?
我可以編寫自己的算法來做到這一點,但我覺得在 C# 中應該有相當於ruby 的人性化。
我用谷歌搜索,但只找到了人性化日期的方法。
例子:
正如@miguel 的回答的評論中所討論的,您可以使用自 .NET 1.1 起可用的TextInfo.ToTitleCase
。 以下是與您的示例相對應的一些代碼:
string lipsum1 = "Lorem lipsum et";
// Creates a TextInfo based on the "en-US" culture.
TextInfo textInfo = new CultureInfo("en-US",false).TextInfo;
// Changes a string to titlecase.
Console.WriteLine("\"{0}\" to titlecase: {1}",
lipsum1,
textInfo.ToTitleCase( lipsum1 ));
// Will output: "Lorem lipsum et" to titlecase: Lorem Lipsum Et
它將忽略所有大寫的大小寫,例如“LOREM LIPSUM ET”,因為它會處理文本中的首字母縮略詞,以便“IEEE”(電氣和電子工程師協會)不會成為“ieee”或“伊”。
但是,如果您只想大寫第一個字符,您可以執行此處的解決方案……或者您可以拆分字符串並大寫列表中的第一個字符:
string lipsum2 = "Lorem Lipsum Et";
string lipsum2lower = textInfo.ToLower(lipsum2);
string[] lipsum2split = lipsum2lower.Split(' ');
bool first = true;
foreach (string s in lipsum2split)
{
if (first)
{
Console.Write("{0} ", textInfo.ToTitleCase(s));
first = false;
}
else
{
Console.Write("{0} ", s);
}
}
// Will output: Lorem lipsum et
使用正則表達式看起來更干凈:
string s = "the quick brown fox jumps over the lazy dog";
s = Regex.Replace(s, @"(^\w)|(\s\w)", m => m.Value.ToUpper());
還有另一個優雅的解決方案:
在項目的靜態類中定義函數ToTitleCase
using System.Globalization;
public static string ToTitleCase(this string title)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(title.ToLower());
}
然后在項目的任何地方使用它作為字符串擴展:
"have a good day !".ToTitleCase() // "Have A Good Day !"
所有的例子似乎首先降低了其他字符,這不是我需要的。
customerName
= CustomerName
<-- 這就是我想要的
this is an example
= This Is An Example
public static string ToUpperEveryWord(this string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
var words = s.Split(' ');
var t = "";
foreach (var word in words)
{
t += char.ToUpper(word[0]) + word.Substring(1) + ' ';
}
return t.Trim();
}
如果您只想將第一個字符大寫,只需將其粘貼到您自己的實用方法中即可:
return string.IsNullOrEmpty(str)
? str
: str[0].ToUpperInvariant() + str.Substring(1).ToLowerInvariant();
還有一個庫方法可以將每個單詞的第一個字符大寫:
http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx
CSS 技術還可以,但只會改變字符串在瀏覽器中的呈現方式。 更好的方法是在發送到瀏覽器之前使文本本身大寫。
上面的大多數實現都可以,但它們都沒有解決如果您有需要保留的混合大小寫單詞,或者如果您想使用真正的標題案例會發生什么的問題,例如:
“在美國哪里學習博士課程”
要么
“國稅局表格 UB40a”
同樣使用 CultureInfo.CurrentCulture.TextInfo.ToTitleCase(string) 會保留大寫單詞,如“sports and MLB 棒球”中的“體育和 MLB 棒球”,但如果整個字符串都為大寫,則會導致問題。
所以我組合了一個簡單的函數,通過將它們包含在 specialCases 和 lowerCases 字符串數組中,允許您保留大寫和混合大小寫單詞並使小單詞小寫(如果它們不在短語的開頭和結尾):
public static string TitleCase(string value) {
string titleString = ""; // destination string, this will be returned by function
if (!String.IsNullOrEmpty(value)) {
string[] lowerCases = new string[12] { "of", "the", "in", "a", "an", "to", "and", "at", "from", "by", "on", "or"}; // list of lower case words that should only be capitalised at start and end of title
string[] specialCases = new string[7] { "UK", "USA", "IRS", "UCLA", "PHd", "UB40a", "MSc" }; // list of words that need capitalisation preserved at any point in title
string[] words = value.ToLower().Split(' ');
bool wordAdded = false; // flag to confirm whether this word appears in special case list
int counter = 1;
foreach (string s in words) {
// check if word appears in lower case list
foreach (string lcWord in lowerCases) {
if (s.ToLower() == lcWord) {
// if lower case word is the first or last word of the title then it still needs capital so skip this bit.
if (counter == 0 || counter == words.Length) { break; };
titleString += lcWord;
wordAdded = true;
break;
}
}
// check if word appears in special case list
foreach (string scWord in specialCases) {
if (s.ToUpper() == scWord.ToUpper()) {
titleString += scWord;
wordAdded = true;
break;
}
}
if (!wordAdded) { // word does not appear in special cases or lower cases, so capitalise first letter and add to destination string
titleString += char.ToUpper(s[0]) + s.Substring(1).ToLower();
}
wordAdded = false;
if (counter < words.Length) {
titleString += " "; //dont forget to add spaces back in again!
}
counter++;
}
}
return titleString;
}
這只是一種快速而簡單的方法 - 如果您想花更多時間在上面,可能會有所改進。
如果您想保留諸如“a”和“of”之類的較小單詞的大寫,則只需將它們從特殊情況字符串數組中刪除即可。 不同的組織對資本化有不同的規定。
您可以在此站點上看到此代碼的示例: Egg Donation London - 該站點通過解析 url 例如“/services/uk-egg-bank/introduction”自動在頁面頂部創建面包屑路徑 - 然后每個路徑中的文件夾名稱將連字符替換為空格並將文件夾名稱大寫,因此 uk-egg-bank 成為 UK Egg Bank。 (保留大寫的“UK”)
此代碼的擴展可能是在共享文本文件、數據庫表或 Web 服務中具有首字母縮略詞和大寫/小寫單詞的查找表,以便可以從一個位置維護混合大小寫單詞列表並應用於許多不同的依賴於該功能的應用程序。
我使用自定義擴展方法實現了相同的目標。 對於第一個子字符串的首字母,請使用yourString.ToFirstLetterUpper()
方法。 對於不包括文章和一些命題的每個子字符串的首字母,請使用yourString.ToAllFirstLetterInUpper()
方法。 下面是一個控制台程序:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("this is my string".ToAllFirstLetterInUpper());
Console.WriteLine("uniVersity of lonDon".ToAllFirstLetterInUpper());
}
}
public static class StringExtension
{
public static string ToAllFirstLetterInUpper(this string str)
{
var array = str.Split(" ");
for (int i = 0; i < array.Length; i++)
{
if (array[i] == "" || array[i] == " " || listOfArticles_Prepositions().Contains(array[i])) continue;
array[i] = array[i].ToFirstLetterUpper();
}
return string.Join(" ", array);
}
private static string ToFirstLetterUpper(this string str)
{
return str?.First().ToString().ToUpper() + str?.Substring(1).ToLower();
}
private static string[] listOfArticles_Prepositions()
{
return new[]
{
"in","on","to","of","and","or","for","a","an","is"
};
}
}
輸出
This is My String
University of London
Process finished with exit code 0.
.NET 中沒有用於正確語言大寫的預構建解決方案。 你想要什么樣的大寫? 您是否遵循《芝加哥風格手冊》慣例? AMA 還是 MLA? 即使是簡單的英語句子大寫也有 1000 多個單詞的特殊例外。 我無法談論 ruby 的 humanize 做了什么,但我想它可能不遵循大寫的語言規則,而是做一些更簡單的事情。
在內部,我們遇到了同樣的問題,不得不編寫相當多的代碼來處理適當的(在我們的小世界中)文章標題的大小寫,甚至不考慮句子大寫。 它確實變得“模糊”:)
這真的取決於你需要什么——你為什么要嘗試將句子轉換為正確的大寫(以及在什么上下文中)?
據我所知,沒有編寫(或抄襲)代碼就沒有辦法做到這一點。 C# nets (ha!) 你的上限、下限和標題(你擁有的)案例:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.