2

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 2
    No, there is no direct alternative for `in` in C, and one cannot exist. Python's `in` (like all other operators) is an extension of the object model: it triggers `obj.__contains__` through a virtual machine instruction. In other words, it is a polymorphic operator. C doesn't have objects and, by extension, doesn't have much in the way of controllable polymorphism. However, that doesn't stop you from writing type-specialised functions that implement `in`-like inclusion testing. As a matter of fact, the standard library provides `strstr`. – Eli Korvigo Jun 27 '19 at 05:29

2 Answers2

5

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
5

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");
}
user3553031
  • 5,990
  • 1
  • 20
  • 40
  • What do you mean by "`strstr` can't be used to check if a given value is stored within an array"? Do you mean it doesn't work for int arrays and the like? – Punugu Aravind Jun 27 '19 at 05:32
  • Correct. strstr searches for a substring within a string. If you want to search for a particular value within an array, your best bet would be to use qsort and a binary search that you write yourself, or write your own search loop (depending on your use scenario). – user3553031 Jun 28 '19 at 00:11