#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM(a) (sizeof(a)/sizeof(*a))
int searchKeyTable(const char* table[], const int size,
const char* key, int* pos)
{
if (table == NULL || key == NULL || pos == NULL)
{
return -1;
}
int n = -1;
for (int i = 0; i < size; i++)
{
if (strcmp(table[i], key) == 0)
{
n = i;
break;
}
}
if (n == -1)
{
printf("无此字符串\n");
return -2;
}
*pos = n + 1;
return 0;
}
int main()
{
char* keywords[] = {
"while",
"case",
"static",
"do"
};
int ret = 0;
int size = NUM(keywords);
int pos = 0;
char* key = "do";
ret = searchKeyTable(keywords, size, key, &pos);
if (ret != 0)
{
printf("searchKeyTable error:%d\n", ret);
return ret;
}
printf("'%s'的位置是:%d\n", key, pos);
printf("\n");
system("pause");
return 0;
}
C语言找数组中指定字符串位置
最新推荐文章于 2025-07-23 00:29:13 发布
这篇博客详细介绍了如何使用C语言编程找到一个特定字符串在字符数组中的位置。通过遍历数组,比较每个元素与目标字符串,最终确定字符串是否存在于数组中及其索引。

349

被折叠的 条评论
为什么被折叠?



