Is there an equivalent to the "in" keyword in python for C

Viewed 564

I'm trying to check if a certain keyword is in the string entered by the user.

This is how I would do it in python.

keyword = "something"
user_input = input("Enter a something: ")
if keyword in user_input: # I don't know how to do this part
    print("You entered something")
else:
    print("You didn't enter something")

How would I do something like that in C?

2 Answers

Not exactly the same, but the closest I can think of is strstr()

#include <string.h>
char *strstr(const char *haystack, const char *needle);

The strstr() function finds the first occurrence of the substring needle in the string haystack.

This function returns a pointer to the beginning of the substring, or NULL if the substring is not found.

You can use strstr() to search for a substring within a string. It's not as generic as Python's in operator (for instance, strstr can't be used to check if a given value is stored within an array), but it will solve the problem that you presented.

For example (untested):

const char *keyword = "something";
const char *user_input = input("Enter a something: "); // I'll leave this to you to implement
if (NULL != strstr(user_input, keyword)) {
    printf("You entered something\n");
} else {
    printf("You didn't enter something\n");
}
Related