我想用 C 语言编写一个字符串数组的二分搜索。
我已经编写了这段代码,它编译时没有错误,但当我尝试搜索时,它没有给出任何结果。任何帮助将不胜感激。
字符串是一个定义类型。很抱歉一开始没有澄清这一点。
//Looks up word s, in dictionary.
bool lookup(string s)
{
int min = 0;
int max = dictionary.size - 1;
int mid;
bool found = false;
while (min <= max && !found)
{
mid = (min + max) /2;
if (dictionary.words[mid].letters == s)
found = true;
else if (dictionary.words[mid].letters > s)
max = mid -1;
else
min = mid + 1;
}
return found;
}
最佳答案
C中的String只是char数组,由于使用==
比较数组只是比较起始地址,所以需要使用库函数strcmp
在 string.h
中比较数组的内容。就像这样:
if (strcmp(dictionary.words[mid].letters, s) == 0)
编辑
我发现尽管有 c
标记,但您还是有某种 string
类型。这是 C 还是 C++?
关于c - C中字符串数组的二分查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14195762/