简体   繁体   English

检查输入字符串是否存在于 C 的字符串数组中

[英]Check if input string exists in array of strings in C

I'm new to C and I'm trying to solve a problem.我是 C 的新手,我正在尝试解决一个问题。

I want to ask for user to insert 5 colors in an array but want to check if string exists on the existing array (allowed colors), or not before it is added.我想要求用户在数组中插入 5 colors 但想检查现有数组中是否存在字符串(允许的颜色),或者在添加之前不存在。 I've tried with strcmp and some other ways but can figure out how to do it.我已经尝试过strcmp和其他一些方法,但可以弄清楚如何去做。 Any help would be appreciated.任何帮助,将不胜感激。

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

char *colors[] = {
    "green",
    "red",
    "blue",
    "yellow",
    "brown",
    "white",
    "black"
};
int n = 5, i, num, size = 7;
char input[5][7];

int main() {
    char *str = (char *)malloc(sizeof(char) * size);

    printf("Add 5 colors:\n ");

    for (i = 0; i < n; i++) {
        scanf("%s", input[i]);
        strcpy(str, input[i]);

        if (strcmp(colors[i], str) == 0) {
            printf("Exists!\n");
        }
    }

    for (int i = 0; i < n; ++i) {
        printf("%d %s\n", 1 + i, input[i]);
    }
    return 0;
}

You should add a nested loop to compare the input with every string in the reference array:您应该添加一个嵌套循环来将输入与引用数组中的每个字符串进行比较:

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

const char *colors[7] = {
    "green",
    "red",
    "blue",
    "yellow",
    "brown",
    "white",
    "black",
};

int main() {
    int n, i, j, num, size = 7;
    char input[5][8];

    printf("Add 5 colors:\n ");

    n = 0;
    while (n < 5) {
        if (scanf("%7s", input[n]) != 1)
            break;

        for (int j = 0; j < 7; i++) {
            if (strcmp(input[n], colors[j]) == 0) {
                printf("Exists!\n");
                n++;
                break;
            }
        }
    }
    for (int i = 0; i < n; ++i) {
        printf("%d %s\n", 1 + i, input[i]);
    }
    return 0;
}

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

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