繁体   English   中英

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

[英]C- to check if a char in a string belongs in an array

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

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

暂无
暂无

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

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