C语言 在字符串列表中匹配一个字符串
时间: 2024-05-03 10:17:06 浏览: 9
在 C 语言中,可以通过使用字符串数组来表示一个字符串列表。要在这个列表中查找一个字符串,可以使用循环结构和字符串比较函数来实现。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char words[][20] = {"apple", "orange", "banana", "grape", "peach"};
char search[20];
int i, found = 0;
printf("Enter a word to search: ");
scanf("%s", search);
for (i = 0; i < 5; i++) {
if (strcmp(words[i], search) == 0) {
found = 1;
break;
}
}
if (found) {
printf("The word %s is found in the list.\n", search);
} else {
printf("The word %s is not found in the list.\n", search);
}
return 0;
}
```
在这个代码中,我们定义了一个字符串数组 `words` 来表示字符串列表,以及一个字符串 `search` 来表示要查找的字符串。然后,我们使用 `for` 循环遍历整个字符串数组,并使用 `strcmp` 函数逐个比较每个字符串是否与要查找的字符串匹配。如果找到匹配的字符串,我们将 `found` 标志设置为 1,并使用 `break` 语句退出循环。最后,我们根据 `found` 标志的值输出相应的结果。