
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a String Contains Any Special Character in C#
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.
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: $ # %
Advertisements