C- 检查字符串中的字符是否属于数组

标签 c arrays string loops char

基本上我想要做的是,当用户输入一个字符串时,我的代码将一个一个地检查字符,看看它们是否属于一个数组。

For instance i have an array:
char example[] = { 'a', 'b', 'c', 'd', 'e' };

假设用户输入了一个字符串“example string” 现在我想单独检查字符串中的每个字符 如果它们存在于给定数组中。所以第一个字母“e”显然在数组中 而给定数组中不存在字母“x”。到目前为止,我正在尝试 使用循环和 memchr,但由于某种原因它无法正常工作,这是我的代码:

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

int main(){
    char array[] = { 'a', 'b', 'c', 'd', 'e' };
    char input[40]; /*Reserved for the string*/
    int lengthofstring,i;
    scanf("%[^\n]s",input); /*This enables spaces in the input, and let's say 
    the string in this case is "example"*/
    lengthofstring=strlen(input);
    for (i=0;i<lengthofstring;i++){
        if (memchr(array,input[i],sizeof(array)){
            /* Now in this example input[i]="e", when i=0 and sizeof(array)=5*/
            printf("The letter %c does exist\n",input[i]);
        }
        else {
            printf("The letter %c does NOT exist\n",input[i]);
        }
    }
}

我真的很难弄清楚这段代码有什么问题,由于某种原因它总是在不存在的类别中结束。非常感谢任何建议或帮助,在此先感谢。

最佳答案

代码似乎对我有用。我确实编辑了问题中的代码,我可能无意中删除了问题。请随时重新编辑并发布原始代码,我似乎无法回滚我的编辑。

工作:

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

int main(){
    char array[] = { 'a', 'b', 'c', 'd', 'e' };
    char input[40]; /*Reserved for the string*/
    int lengthofstring,i;
    scanf("%[^\n]s",input); /*This enables spaces in the input, and let's say 
    the string in this case is "example"*/
    lengthofstring=strlen(input);
    for (i=0;i<lengthofstring;i++){
        if (memchr(array,input[i],sizeof(array))) {
            /* Now in this example input[i]="e", when i=0 and sizeof(array)=5*/
            printf("The letter %c does exist\n",input[i]);
        }
        else {
            printf("The letter %c does NOT exist\n",input[i]);
        }
    }
}

我在 if 语句上添加了 2 个结束 } 和一个结束 )

原代码:

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

int main(){
char array[] = { 'a', 'b', 'c', 'd', 'e' };
char input[40]; /*Reserved for the string*/
int lengthofstring,i;
scanf("%[^\n]s",input); /*This enables spaces in the input, and let's say 
the string in this case is "example"*/
lengthofstring=strlen(input);
for (i=0;i<lengthofstring;i++){
if (memchr(array,input[i],sizeof(array)){
/* Now in this example input[i]="e", when i=0 and sizeof(array)=5*/
printf("The letter %c does exist\n",input[i]);}
else {
printf("The letter %c does NOT exist\n",input[i]);}

关于C- 检查字符串中的字符是否属于数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17129070/

相关文章:

c++ - Visual Studio C 或 C++ 中的最大值

java - 在 Java 中创建数组对象?

arrays - 如果 PowerShell 中不包含任何数组值,则写出字符串

ruby - 如何输出转义字符?

python - 如何仅通过一次交换找到字符串的所有可能排列?

c - 为什么这个作业会破坏我的程序?

c++ - C++ 中的 _In_ 是什么?

c - 确定小端机器地址的十六进制值

python - numpy中两个数组的乘法

ios - 按特定键对字典数组进行排序