16

I'm fairly new to C programming, how would I be able to check that a string contains a certain character for instance, if we had:

void main(int argc, char* argv[]){

  char checkThisLineForExclamation[20] = "Hi, I'm odd!"
  int exclamationCheck;
}

So with this, how would I set exclamationCheck with a 1 if "!" is present and 0 if it's not? Many thanks for any assistance given.

Alex
  • 394
  • 1
  • 4
  • 15
  • 3
    Consider the [`strchr()`](https://linux.die.net/man/3/strchr) or [`strcspn()`](https://linux.die.net/man/3/strcspn) function. – John Bollinger Sep 28 '19 at 13:29
  • 4
    And if you're not supposed to use standard functions, it shouldn't be too hard to iterate over all the characters of the string, comparing each character against the one you want to find. If you don't know how to do that, then please go back to your text-book and read more about loops and strings. – Some programmer dude Sep 28 '19 at 13:30

2 Answers2

21

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

You can use plain search for ! character with

Code

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

int main(void)
{
    char str[] = "Hi, I'm odd!";
    int exclamationCheck = 0;
    int i=0;
    while (str[i]!='\0'){
        if (str[i]=='!'){
            exclamationCheck = 1;
            break;
        }
        i++;
    }
    printf("exclamationCheck = %d\n", exclamationCheck);
    return 0;
}
EsmaeelE
  • 2,331
  • 6
  • 22
  • 31