首页 > 解决方案 > 获取定义为 uint8 的字符串数组中特定字符串的索引

问题描述

我有以下情况:

数组定义为无符号整数:

uint8 myArray[6][10] = {"continent","country","city","address", "street", "number"};

现在我想获取例如字符串“city”的索引。我想做这样的事情:

uint8 idx;

for(idx = 0; idx < sizeof(myArray)/sizeof(myArray[0];i++))
{
    if((myArray[idx]) == "city")   // This can not work because the array is an uint8 array
    {
         /*idx = 2 ....*/
    }
}

不使用 string.h 中的函数(如 strcpy 等)的正确方法是什么...

标签: cmultidimensional-array

解决方案


正如其他人指出的那样,您不能将两个 C 字符串与等号运算符进行比较=,而是需要使用strcmp,并且由于不允许使用它,因此您需要自己实现它。

这里是glibc中strcmp的实现

所以你的代码可以是这样的:

int mystrcmp(const uint8 *s1, const uint8 *s2)
{
    uint8 c1, c2;
    do
    {
        c1 = *s1++;
        c2 = *s2++;
        if (c1 == '\0')
            return c1 - c2;
    }
    while (c1 == c2);
    return c1 - c2;
}
....
uint8 *str = "city";
size_t size = sizeof(myArray) / sizeof(myArray[0]);
size_t idx;

for (idx = 0; idx < size; i++)
{
    if (mystrcmp(myArray[idx], str) == 0)
    {
        break;
    }
}
if (idx == size)
{
    printf("'%s' was not found\n", str);
}
else
{
    printf("'%s' was found at index %zu\n", str, idx);
}

推荐阅读