使用 C# 正則表示式列印字串中每個單詞的首字母


假設我們的字串為 -

string str = "The Shape of Water got an Oscar Award!";

使用以下正則表示式顯示每個單詞的首字母 -

@"\b[a-zA-Z]"

以下是完整的程式碼 -

示例

 即時演示

using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
   public class Program {
      private static void showMatch(string text, string expr) {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc) {
            Console.WriteLine(m);
         }
      }
      public static void Main(string[] args) {
         string str = "The Shape of Water got an Oscar Award!";
         Console.WriteLine("Display first letter of each word!");
         showMatch(str, @"\b[a-zA-Z]");
      }
   }
}

輸出

Display first letter of each word!
The Expression: \b[a-zA-Z]
T
S
o
W
g
a
O
A

更新於: 22-Jun-2020

363 次瀏覽

開啟您的 職業生涯

完成此課程以獲得認證

開始
廣告
© . All rights reserved.