2009-05-26 79 views
48

我可以寫我自己的算法來做到這一點,但我覺得應該有相當於C#中的ruby's humanize如何用C#將每個單詞的第一個字符或整個字符串的第一個字符大寫?

我搜索了它,但只找到方法來人性化日期。

實例:

  • 開啓 「的Lorem Lipsum的Et」 到 「的Lorem lipsum等」
  • 開啓 「的Lorem lipsum等」 到 「的Lorem Lipsum Et」 是
+1

我喜歡說Lorem Lipsum出於某種原因^^ – marcgg 2009-05-26 22:45:47

+3

總是有正則表達式! string strToCap = strSource.ToLower(); Regex rCapitalize = new Regex(「(?<= [!\。?] \ s +)[A-Za-z]」); strToCap = rCapitalize.Replace(strToCap,m => {return m.Value.ToUpper();}); ...但你會有兩個問題。:) – rijipooh 2009-05-26 23:07:27

+3

由於接受的答案鏈接到與原始問題相反的代碼,因此我編輯了問題以詢問兩個方向,希望這個問題對於未來的用戶不會完全混淆。偶然發現。 – 2009-05-27 06:27:42

回答

90

正如在@miguel's answer的評論中所討論的那樣,您可以使用自.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」,因爲它走的情況下照顧,如果首字母縮寫詞是在文本文件(讓「NAMBLA」將不會成爲「nambla」或「Nambla」)。

但是,如果你只是想利用的第一個字符,你可以做的解決方案,在here ...或者你可以只拆分字符串,並利用該列表中的第一個:

string lipsum2 = "Lorem Lipsum Et"; 

string lipsum2lower = textInfo.ToLower(lipsum1); 

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 
2
一種方法的一種方式

如果你只是想利用的第一個字符,只要堅持這自己的實用方法:

return string.IsNullOrEmpty(str) 
    ? str 
    : str[0].ToUpperInvariant() + str.Substring(1).ToLowerInvariant(); 

還有一個圖書館的方法來利用每個單詞的第一個字符:

http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx

+0

這隻會給你標題案例:「Lorem Ipsum Et」,而不是句子:「Lorem ipsum et」,對嗎? – vinny 2009-05-26 22:36:46

0

有在.NET語言正確不captialization預置的解決方案。你想要什麼樣的資本化?你是否遵循芝加哥風格公約手冊? AMA還是MLA?即使簡單的英語句子大寫也有1000個字的特殊例外。我不能說紅寶石的人性化做什麼,但我想它可能不符合大寫的語言規則,而是做更簡單的事情。

在內部,我們遇到了同樣的問題,不得不寫一個相當大的代碼來處理正確的(在我們的小世界中)文章標題的框架,甚至沒有考慮句子的大小寫。它確實得到了「模糊」:)

這真的取決於你需要什麼 - 爲什麼你想把句子轉換成合適的大寫(以及在什麼情況下)?

0

CSS技術好的,但只能改變瀏覽器中字符串的表示。更好的方法是在發送到瀏覽器之前使文本本身大寫。

上述大部分implimentations的都OK,但它們都沒有解決,如果你已經混了需要保留,或者如果你想使用真正的標題案例,例如情況下的話會發生什麼問題:

「在哪裏學習PHD課程在美國」

「IRS表UB40a」

另外使用CultureInfo.CurrentCulture.TextInfo.ToTitleCase(字符串)保留大寫單詞作爲 「體育和MLB棒球」變成「體育和MLB棒球」,但是如果整個字符串被放在大寫字母,那麼這導致問題。

因此,我將一個簡單的函數放在一起,使您可以保留大寫和混合大小寫的單詞,並通過將它們包含在特殊案例和較小案例中來製作小寫字母小寫字母(如果它們不在該短語的開頭和結尾處)字符串數組:

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 - 此網站通過解析網址(例如「/ services/uk-egg-bank/introduction」)自動在網頁頂部創建麪包屑路徑 - 那麼路徑中的每個文件夾名稱都會將連字符替換爲空格並將文件夾名稱大寫,所以uk-egg-bank成爲UK Egg Bank。 (保留大寫「英國」)

此代碼的擴展可能是在共享文本文件,數據庫表或Web服務中使用縮寫詞和大寫/小寫詞的查找表,以便混合大小寫的列表單詞可以從一個地方進行維護,並適用於依賴於該功能的許多不同應用程序。

19

使用這個正則表達式看起來清爽多了:

string s = "the quick brown fox jumps over the lazy dog"; 
s = Regex.Replace(s, @"(^\w)|(\s\w)", m => m.Value.ToUpper()); 
2

還有另一種優雅的解決方案:

定義功能ToTitleCase靜態類你謨的

using System.Globalization; 

public static string ToTitleCase(this string title) 
{ 
    return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(title); 
} 

然後在項目的任何地方使用它就像一個字符串擴展名:

"have a good day !".ToTitleCase() // "Have A Good Day !" 
相關問題