Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how can check weather a string Contain numbers special Char etc
Posted

You might try below,

C#
class Program
{
    static void Main(string[] args)
    {
        string randomCharacters = "HelloWorld2090!!!@#$";
        var result = randomCharacters.Any(ch => Char.IsNumber(ch) || Char.IsPunctuation(ch) || Char.IsSymbol(ch));
        Console.WriteLine(result);
    }
}


Hope it helps :)
 
Share this answer
 
The Solution 1 given by Richard MacCutchan is very good.
As an alternative if you want to check whether the string contains a particular category of characters say Punctuation or Numbers etc., then the System.Text.RegularExpressions.Regex class can be considered to test as shown below:
C#
string text = "Is this text, contains special chars?";
//The Regex pattern matches if atleast one character of the
//alternatives is found \p{P} Unicode punctuation category
//\p{N} Unicode numbers category
if(System.Text.RegularExpressions.Regex.IsMatch(text,@"\p{P}|\p{N}"))
    Console.WriteLine ("Contains special chars");
else
    Console.WriteLine ("Does not contain special chars");

//Output
//Contains special chars
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 16-Apr-12 22:29pm    
A valid alternative, a 5.
--SA
VJ Reddy 16-Apr-12 23:31pm    
Thank you very much, SA.
IndexOfAny()[^] looks like a good choice.
 
Share this answer
 
Comments
VJ Reddy 16-Apr-12 11:21am    
Good link. 5!
Sergey Alexandrovich Kryukov 16-Apr-12 22:29pm    
Agree, a 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900