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

CsharpServer Side ProgrammingProgramming

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:
$
#
%
raja
Published on 24-Jul-2018 12:46:13
Advertisements