gpt4 book ai didi

c - 从c中的数组中删除字符串

转载 作者:行者123 更新时间:2023-11-30 19:42:07 25 4
gpt4 key购买 nike

我有一个程序可以调用字符串上的白色、黑色、蓝色、红色和黄色。所以我的问题是我将如何检查输入了哪些字符串,然后打印未调用的颜色。

例如。如果。在我的函数中输入了白色、黑色、蓝色、黄色作为字符串,程序需要 printf red,这是一种可能性,例如狗、白色、鲸鱼、蓝色、黑色、红色等无效输入应该打印出黄色

const char *string[5];
string[0] = "White";
string[1] = "Black";
string[2] = "Blue";
string[3] = "Red";
string[4] = "Yellow";

gets(string);
printf(//);

最佳答案

您可以简化字符串的声明,它应该是 const 因为我们不会修改它:

const char *strings[] = { "white", "black", "blue", "red", "yellow" };

然后我们可以使用整数的位来表示输入的字符串中的值:

unsigned int flags = 0; /* Zero has no bits set => nothing input so far. */

当我们收到输入时,我们会在strings中查找匹配项,并在flags中设置相应的位:

char input[1024];

if(fgets(input, sizeof input, stdin) != NULL)
{
const size_t len = strlen(input);
while(len > 0 && input[len - 1] == '\n')
input[--len] = '\0';
for(size_t i = 0; i < sizeof strings / sizeof *strings; ++i)
{
if(strcmp(strings[i], input) == 0)
flags |= 1 << i;
}
}

然后最后打印所有没有见过的字符串:

for(size_t i = 0; i < sizeof strings / sizeof *strings; ++i)
{
if((flags & (1 << i)) == 0)
printf("%s\n", strings[i]);
}

我希望您应该能够使用上述内容来获得您想要的东西。

关于c - 从c中的数组中删除字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32756293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com