【问题标题】:Get index of a specific string in string array which is defined as uint8获取定义为 uint8 的字符串数组中特定字符串的索引
【发布时间】:2020-03-06 09:15:58
【问题描述】:

我有以下情况:

数组定义为无符号整数:

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 等)的正确方法是什么...

【问题讨论】:

标签: c multidimensional-array


【解决方案1】:

正如其他人指出的,你不能用相等运算符=比较两个C字符串,而是你需要使用strcmp,并且由于你不允许使用它,你需要自己实现它。

这里实现strcmp in glibc

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

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);
}

【讨论】:

  • 这个解决方案很好用!但是如何解决编译器警告:"pointers to different types at assignment" uint8 *str = "city"; ?
  • 使用演员表:uint8 *str = (uint8 *)"city";
【解决方案2】:

您需要逐个字符地比较字符串。

为此,您编写一个循环,从第一个字符开始,直到在任一字符串中找到不匹配的字符或字符串结束标记,以先到者为准。

因为听起来像作业,我就不贴代码了。

【讨论】:

  • 我找到了解决方案。谢谢!这不是任何家庭作业或类似的。只是自己训练以提高一些c技能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多