gpt4 book ai didi

c - 如何在 C 编程中搜索二维字符串数组中的单词

转载 作者:行者123 更新时间:2023-11-30 15:47:33 26 4
gpt4 key购买 nike

如何在二维字符串数组中搜索整个单词。此代码仅输出我输入的单词的第一个字母。

谁能帮我解决这个问题吗?

该索引如何仅在函数中传递我从该搜索中找到的索引。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#define PEOPLE 4
#define LEN_NAME 30

int main (void)
{
int i;
char found_name;
char name[PEOPLE][LEN_NAME]= {"John Lucas","Armanod Jonas",
"Jack Richard","Donovan Truck"};

printf("What name do you want to search?\n>");
scanf("\n%s", &found_name);
for (i = 0 ; i < PEOPLE; i ++)
{
if (strchr(name[i], found_name ) != NULL)
{
printf( "Found %c in position %d,%s\n", found_name, i+1, name[i]);
printf( " index of player is %d.\n",i +1);
}
}
return 0;
}

最佳答案

您需要将found_name设为字符数组,而不是字符。另外,您需要使用 strstr(搜索字符串)而不是 strchr(搜索单个字符)进行搜索。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#define PEOPLE 4
#define LEN_NAME 30
int main(void)
{
int i;
char found_name[LEN_NAME];
char name[PEOPLE][LEN_NAME] = { "John Lucas", "Armanod Jonas",
"Jack Richard", "Donovan Truck"
};

printf("What name do you want to search?\n>");
scanf("%29s", found_name);
for (i = 0; i < PEOPLE; i++) {
if (strstr(name[i], found_name) != NULL) {
printf("Found %c in position %d,%s\n", found_name, i + 1,
name[i]);
printf(" index of player is %d.\n", i + 1);
}
}
return 0;
}

关于c - 如何在 C 编程中搜索二维字符串数组中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17323748/

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