0

In c, to search for the letters a-z, I can do the following loop:

char s[10];
int c;
int has_letter = 0;

for (int i=0; (c=s[i])!='\0'; i++) {
    if (c>='a' && c<='z')
        has_letter = 1;
}

However, what the are chars are not contiguous, for example:

// see if any of the following letters are in it: 'adiuo'
char s[10];
int c;
int has_letter = 0;

for (int i=0; (c=s[i])!='\0'; i++) {
    if (c=='a' || c=='d' || c=='i' || c=='u' || c=='o')
        has_letter = 1;
}

Is there a way to simplify that construction? For example, doing something like:

char s[10];
int c;
int has_letter = 0;

for (int i=0; (c=s[i])!='\0'; i++) {
    if (c in "adiuo") // possible to do something like this?
        has_letter = 1;
}
  • The code you posted fails to initialize `has_letter` before entering the loop, so there's no telling what value it will have unless the loop assigns `1` to it. – Tom Karzes Aug 26 '19 at 21:21
  • You've couched the question in terms of testing individual characters one at a time, but for what your example code accomplishes, you don't need much more than a single call to `strcspn()` to test *all* the characters of `s` in one go. – John Bollinger Aug 26 '19 at 23:46

3 Answers3

4

strpbrk() does exactly what I think you want to do. You use it like

const char mask[] = "adiuo";

if ( strpbrk( str, mask ) ) {
  //do whatever...
} 

The function returns a pointer to the first character in str that appears in the string mask. If it's non null, it's there.

yhyrcanus
  • 3,743
  • 2
  • 23
  • 28
2

Just for this there is a helper function from string.h:

if (strchr("adiuo", c) != NULL)

The strchr() function returns a pointer to the first occurrence of the character in the string or NULL if the character is not found. So just check if it returns not NULL, which means a character was found in the string.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
-1
char s[10];
int c, has_letter;

const char* letters = "adiuo";

has_letter = 0;
for (int i=0; (c=s[i])!='\0'; i++) {
    if (strchr(letters, c) != NULL) {
        has_letter = 1;
        break;
    }
}
Sam Kumar
  • 428
  • 4
  • 8