C# program to check if a string contains any special character


To check if a string contains any special character, you need to use the following method −

Char.IsLetterOrDigit

Use it inside for loop and check or the string that has special characters.

Let us say our string is −

string str = "Amit$#%";

Now convert the string into character array −

str.ToCharArray();

With that, use a for loop and to check for each character using the isLetterOrDigit() method.

Example

Let us see the complete code.

Live Demo

using System;
namespace Demo {
   class myApplication {
      static void Main(string[] args) {
         string str = "Amit$#%";
         char[] one = str.ToCharArray();
         char[] two = new char[one.Length];
         int c = 0;
         for (int i = 0; i < one.Length; i++) {
            if (!Char.IsLetterOrDigit(one[i])) {
               two[c] = one[i];
               c++;
            }
         }
         Array.Resize(ref two, c);
         Console.WriteLine("Following are the special characters:");
         foreach(var items in two) {
            Console.WriteLine(items);
         }
         Console.ReadLine();
      }
   }
}

Output

Following are the special characters:
$
#
%

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 19-Jun-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements