如何在 C# 中將字串轉換為首字母大寫形式?


標題形式是任意文字,例如標題或章標題,主要單詞的首字母大寫。標題形式或標題形式是一種大寫形式,用於呈現英語中已釋出作品或藝術作品的標題。使用標題形式時,除“次要”單詞外,所有單詞都大寫,除非它們是標題的第一個或最後一個單詞。

示例中 ToTitleCase 的當前實現產生的輸出字串與輸入字串等長。

示例 1

class Program{
   static void Main(string[] args){
      string myString = "wAr aNd pEaCe";
      TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
      Console.WriteLine("\"{0}\" to titlecase: {1}", myString, myTI.ToTitleCase(myString));
      Console.ReadLine();
   }
}

輸出

"war and peace" to titlecase: War And Peace

示例 2

class Program{
   static void Main(string[] args){
      string[] values = {
         "a tale of three cities", "gROWL rescue",
         "inside the office", "sports and tennis",
         "The Return of Christmas Holmes"
      };
      TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
      foreach (var value in values)
      Console.WriteLine("{0} −−> {1}", value, ti.ToTitleCase(value));
      Console.ReadLine();
   }
}

輸出

a tale of three cities −−> A Tale Of Three Cities
gROWL rescue −−> Growl Rescue
inside the office −−> Inside The Office
sports and tennis −−> Sports And Tennis
The Return of Christmas Holmes −−> The Return Of Christmas Holmes

更新於: 05-11-2020

644 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

入門
廣告
© . All rights reserved.