How to find the first occurrence of one of several characters (other than using regex)

sskanitk picture sskanitk · Oct 11, 2012 · Viewed 9.1k times · Source

After going through a bunch of threads, I know that I need to use regex.h for using regular expressions in C & C++.

But I was wondering, is there an easier way to search for occurrence of "/" or "\" in a string.

// I have a strstr statement like this -
str = strstr(s, "/");

I was wondering if it is possible to change it so that I can search for the first occurrence of a / or \ in a single call to strstr.

Answer

Mark Tolonen picture Mark Tolonen · Oct 11, 2012

Try strcspn:

Get span until character in string
Scans str1 for the first occurrence of any of the characters that are part of str2, returning the number of characters of str1 read before this first occurrence.

The search includes the terminating null-characters. Therefore, the function will return the length of str1 if none of the characters of str2 are found in str1.

Example:

#include <stdio.h>
#include <string.h>

const char* findany(const char* s, const char* keys)
{
    const char* tmp;
    tmp = s + strcspn(s,keys);
    return *tmp == '\0' ? NULL : tmp;
}

int main ()
{
  char str1[] = "abc\\123";
  char str2[] = "abc/123";
  char str3[] = "abc123";
  char keys[] = "/\\";
  printf("1: %s\n",findany(str1,keys));
  printf("2: %s\n",findany(str2,keys));
  printf("3: %s\n",findany(str3,keys));
  return 0;
}

Edit: strpbrk does the same thing as findany above. Didn't see that function:

#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[] = "abc\\123";
  char str2[] = "abc/123";
  char str3[] = "abc123";
  char keys[] = "/\\";
  printf("1: %s\n",strpbrk(str1,keys));
  printf("2: %s\n",strpbrk(str2,keys));
  printf("3: %s\n",strpbrk(str3,keys));
  return 0;
}

Output (of both):

1: \123
2: /123
3: (null)