strstr function-check if a string is included

Use the strstr function to check if a string is included. You can use the strstr function by loading string.h.

#include <string.h>
char * strstr (const char * str1, const char * str2);

If str1 contains str2, the first matching address is returned. If not found, returns NULL.

In C language, there is a promise that string ends with "\ 0". The strstr function presupposes this convention and searches for a string.

When using the strstr function, make sure that the two strings of the argument end with "\ 0".

Check if a string is included

This is a sample to check if a string is included with the strstr function. Make sure it's not NULL and you're good to go.

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

int main (void) {
  const char * message = "I like orange\n";
  const char * match = "orange";
  
  if (strstr (message, match)! = NULL) {
    printf("Match\n");
  }
  else {
    printf("Not Match\n");
  }
}

This is the output result.

Match

Count the number of strings included

The strstr function returns the position when there is a match, so let's use this to count the number of strings included.

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

int main (void) {
  const char * message = "I like orangeorange and orange. \ N";
  const char * match = "orange";
  int32_t match_length = strlen (match);
  
  int32_t match_count = 0;
  const char * message_ptr = message;
  while (1) {
    message_ptr = strstr (message_ptr, match);
    if (message_ptr! = NULL) {
      match_count ++;
      message_ptr + = match_length;
    }
    else {
      break;
    }
  }
  
  printf("Match Count%d\n", match_count);
}

This is the output result.

Match Count 3

Associated Information