C# program to check if a string contains special characters

王林
Release: 2023-09-22 16:57:03
forward
1408 people have browsed it

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
Copy after login

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

Suppose our string is -

string str = "Amit$#%";
Copy after login

Now convert the string to character array -

str.ToCharArray();
Copy after login

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();
      }
   }
}
Copy after login

Output

Following are the special characters:
$
#
%
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!