在 C 中 - 检查字符数组中是否存在字符 [英] In C - check if a char exists in a char array
本文介绍了在 C 中 - 检查字符数组中是否存在字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试检查一个字符是否属于无效字符列表/数组.
I'm trying to check if a character belongs to a list/array of invalid characters.
来自 Python 背景,我曾经只能说:
Coming from a Python background, I used to be able to just say :
for c in string:
if c in invalid_characters:
#do stuff, etc
如何使用常规 C 字符数组执行此操作?
How can I do this with regular C char arrays?
推荐答案
等效的 C 代码如下所示:
The equivalent C code looks like this:
#include <stdio.h>
#include <string.h>
// This code outputs: h is in "This is my test string"
int main(int argc, char* argv[])
{
const char *invalid_characters = "hz";
char *mystring = "This is my test string";
char *c = mystring;
while (*c)
{
if (strchr(invalid_characters, *c))
{
printf("%c is in \"%s\"\n", *c, mystring);
}
c++;
}
return 0;
}
注意 invalid_characters 是一个 C 字符串,即.一个以 null 结尾的 char
数组.
Note that invalid_characters is a C string, ie. a null-terminated char
array.
这篇关于在 C 中 - 检查字符数组中是否存在字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文