Home  >  Article  >  Backend Development  >  C# program to check if a string contains special characters

C# program to check if a string contains special characters

王林
王林forward
2023-09-22 16:57:031540browse

C# program to check if a string contains special characters

To check if a string contains special characters you need to use the following method -

Char.IsLetterOrDigit

Use it in a for loop and check if it contains special characters string.

Suppose our string is -

string str = "Amit$#%";

Now convert the string to character array -

str.ToCharArray();

Use for loop and check each character using isLetterOrDigit() method.

Example

Let’s look at 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:
$
#
%

The above is the detailed content of C# program to check if a string contains special characters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete