w3resource

C# Sharp Exercises: Find a specific word in a string

C# Sharp Regular Expression: Exercise-9 with Solution

Write a C# Sharp program to locate the word “C#” in a given string. If the word "C#" is found, return “C# document found.” otherwise return “Sorry no C# document!”.

Sample Data:
("C# Exercises") -> "C# document found."
("Python Exercises") -> "Sorry no C# document!"
("Tutorial on c#") -> "C# document found."

Sample Solution:

C# Sharp Code:

using System;
using System.Text.RegularExpressions;
namespace exercises
{
   class Program
   {
       static void Main(string[] args)
       {
           string text = "C# Exercises";
           Console.WriteLine("Original string: " + text);
           Console.WriteLine(test(text));
           text = "Python Exercises";
           Console.WriteLine("\nOriginal string: " + text);
           Console.WriteLine(test(text));
           text = "Tutorial on c#";
           Console.WriteLine("\nOriginal string: " + text);
           Console.WriteLine(test(text));
       }


       public static string test(string text)
       {
           bool flag = Regex.IsMatch(text, Regex.Escape("C#"), RegexOptions.IgnoreCase);
           if (flag)
           {
               return "C# document found.";
           }
           return "Sorry no C# document!";
       }
   }
}

Sample Output:

Original string: C# Exercises
C# document found.

Original string: Python Exercises
Sorry no C# document!

Original string: Tutorial on c#
C# document found.

Flowchart:

Flowchart: C# Sharp Exercises - Find a specific word in a string.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous C# Sharp Exercise: Remove special characters from a given text.
Next C# Sharp Exercise: C# Sharp Regular Expression Exercises Home.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.