Print first letter of each word in a string using C# regex


Let’s say our string is −

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

Use the following Regular Expression to display first letter of each word −

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

Here is the complete code −

Example

 Live Demo

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]");
      }
   }
}

Output

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

Updated on: 22-Jun-2020

306 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements