Manish
Manish

Reputation: 6286

How to find whether a string contains any of the special characters?

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 characters in the string?

Upvotes: 25

Views: 106762

Answers (11)

Hari bhagya sri
Hari bhagya sri

Reputation: 1

def splchar(str):
splchar=("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "+", "=")
for chr in splchar:
    if (chr in str):
        print("not accepted")
        break
else:
        print("accepted")
str="GeeksForGeeks"

splchar(str)

Upvotes: -1

Mike B.
Mike B.

Reputation: 144

Linq is the new black.

string.Any(c => char.IsSymbol(c));

For IsSymbol(), valid symbols are members of UnicodeCategory.

  • Letterlike symbols, which include a set of mathematical alphanumeric symbols as well as symbols such as ℅, №, and ™
  • Number forms, such as subscripts and superscripts
  • Mathematical operators and arrows
  • Geometric symbols
  • Technical symbols
  • Braille patterns
  • Dingbats

Edit:

This does not catch ALL characters. This may supplement:

string.Any(c => !char.IsLetterOrDigit(c));

Upvotes: 9

Filix Mogilevsky
Filix Mogilevsky

Reputation: 777

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);
}

Upvotes: 5

Arpita Sarkar
Arpita Sarkar

Reputation: 11

//apart from regex we can also use this
string input = Console.ReadLine();
            char[] a = input.ToCharArray();
            char[] b = new char[a.Length];
            int count = 0;
            for (int i = 0; i < a.Length; i++)
            {
                if (!Char.IsLetterOrDigit(a[i]))
                {
                    b[count] = a[i];
                    count++;
                }
            }
            Array.Resize(ref b, count);
            foreach(var items in b)
            {
                Console.WriteLine(items);
            }
            Console.ReadLine();
//it will display the special characters in the string input

Upvotes: 1

Khamul
Khamul

Reputation: 51

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.

Upvotes: 1

Ziggler
Ziggler

Reputation: 3500

public static bool HasSpecialCharacters(string str)
{
  string specialCharacters = @"%!@#$%^&*()?/>.<,:;'\|}]{[_~`+=-" +"\"";
  char[] specialCharactersArray = specialCharacters.ToCharArray();

  int index = str.IndexOfAny(specialCharactersArray);
  //index == -1 no special characters
  if (index == -1)
    return false;
  else
    return true;
}

Upvotes: 0

Manish Basantani
Manish Basantani

Reputation: 17499

Also...

foreach (char character in "some*!@#@!#string")
        {
            if(!Char.IsLetterOrDigit(character))
            {
                //It is a special character.
            }
        }

Upvotes: -1

Adam
Adam

Reputation: 15

Using PHP, you can try:

if (preg_match("[^A-Za-z0-9]", $yourString) {
  //DO WHATEVER
}

This will return TRUE if the string contains anything other than a letter or number.

Hope this helps.

Upvotes: -2

Mark Byers
Mark Byers

Reputation: 837996

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.

Upvotes: 13

FiveTools
FiveTools

Reputation: 6030

  Regex RgxUrl = new Regex("[^a-z0-9]");
                    blnContainsSpecialCharacters = RgxUrl.IsMatch(stringToCheck);

Upvotes: 13

Jon Skeet
Jon Skeet

Reputation: 1499870

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.

Upvotes: 40

Related Questions