I want to find whether a string contains any of the special characters like !,@,#,$,%,^,&,*,(,)....etc.
How can I do that without looping thorugh all the charact
Linq is the new black.
string.Any(c => char.IsSymbol(c));
For IsSymbol(), valid symbols are members of UnicodeCategory.
Edit:
This does not catch ALL characters. This may supplement:
string.Any(c => !char.IsLetterOrDigit(c));
Here is a short solution to check for special chars using LINQ
private bool ContainsSpecialChars(string value)
{
var list = new[] {"~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "+", "=", "\""};
return list.Any(value.Contains);
}
I was trying to accomplish a different result. To create a method which returns the special character used to separate a determined string, say 1#4#5, to then use it to Split that same string. Since the sistem I am maintaining is built by so many different people, and in some cases, I have no idea which is the pattern(Usually there's none), the following helped me a lot. And I cant vote up as yet.
public String Separator(){
**String specialCharacters = "%!@#$#^&*()?/>.<:;\\|}]{[_~`+=-" +"\"";**
char[] specialCharactersArray = specialCharacters.toCharArray();
char[] a = entrada.toCharArray();
for(int i = 0; i<a.length; i++){
for(int y=0; y < specialCharactersArray.length; i++){
if(a[i] == specialCharactersArray[y]){
separator = String.valueOf(specialCharactersArray[y]);
}
}
}
return separator;
}
Thank you guys.
Use String.IndexOfAny:
private static readonly char[] SpecialChars = "!@#$%^&*()".ToCharArray();
...
int indexOf = text.IndexOfAny(SpecialChars);
if (indexOf == -1)
{
// No special chars
}
Of course that will loop internally - but at least you don't have to do it in your code.
Also...
foreach (char character in "some*!@#@!#string")
{
if(!Char.IsLetterOrDigit(character))
{
//It is a special character.
}
}
Instead of checking if a string contains "special characters" it is often better to check that all the characters in the string are "ordinary" characters, in other words use a whitelist instead of a blacklist. The reason is that there are a lot of characters that could be considered "special characters" and if you try to list them all you are bound to miss one.
So instead of doing what you asked it might be better to check for example that your string matches the regex @"^\w+$"
, or whatever you need.