How do I check if a string contains a certain character?

By using strchr(), like this for example:

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

int main(void)
{
  char str[] = "Hi, I'm odd!";
  int exclamationCheck = 0;
  if(strchr(str, '!') != NULL)
  {
    exclamationCheck = 1;
  }
  printf("exclamationCheck = %d\n", exclamationCheck);
  return 0;
}

Output:

exclamationCheck = 1

If you are looking for a laconic one liner, then you could follow @melpomene’s approach:

int exclamationCheck = strchr(str, '!') != NULL;

If you are not allowed to use methods from the C String Library, then, as @SomeProgrammerDude suggested, you could simply iterate over the string, and if any character is the exclamation mark, as demonstrated in this example:

#include <stdio.h>

int main(void)
{
  char str[] = "Hi, I'm odd";
  int exclamationCheck = 0;
  for(int i = 0; str[i] != '\0'; ++i)
  {
    if(str[i] == '!')
    {
      exclamationCheck = 1;
      break;
    }
  }
  printf("exclamationCheck = %d\n", exclamationCheck);
  return 0;
}

Output:

exclamationCheck = 0

Notice that you could break the loop when at least one exclamation mark is found, so that you don’t need to iterate over the whole string.


PS: What should main() return in C and C++? int, not void.

Leave a Comment