简体   繁体   English

在Python的python中是否有等效的“in”关键字

[英]Is there an equivalent to the “in” keyword in python for C

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. 我就是这样在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? 我怎么会在C中做那样的事情?

Not exactly the same, but the closest I can think of is strstr() 不完全相同,但我能想到的最接近的是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 . strstr()函数在字符串haystack查找第一次出现的子串needle

This function returns a pointer to the beginning of the substring, or NULL if the substring is not found. 此函数返回指向子字符串开头的指针,如果未找到子字符串,则返回NULL

You can use strstr() to search for a substring within a string. 您可以使用strstr()来搜索字符串中的子字符串。 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. 它并不像一般的Python的in运营商(例如, strstr不能被用来检查一个给定的值存储在阵列中),但它会解决您提出的问题。

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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM