c - 获取定义为 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 等)的正确方法是什么...
解决方案
正如其他人指出的那样,您不能将两个 C 字符串与等号运算符进行比较=
,而是需要使用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);
}
推荐阅读
- sql - 按升序对 varchar 列进行数字排序
- java - java.sql.SQLException:列“名称”的值超出范围:值 Finn
- javascript - 处理 jQuery 冲突
- arrays - 如何在 TypeScript 中创建从 1 到 N 的数组?
- pandas - 根据条件组合两个大小不等的数据帧
- java - Windows net.exe 使用驱动程序消息在 Java 上具有无效字符
- regex - 如何使用正则表达式处理负面的前瞻性/落后性?
- javascript - 在 JavaScript 中按对象内的对象排序
- angular - Angular - 导航前显示侧边栏
- r - DNBuilder Shinyapps:更改术语标签