我是 C 语言新手,作为练习,我正在创建库来处理字符串。
现在我正在创建一个名为“indexOf”的函数,它返回字符串中放置字符的索引。
main.c(阅读代码注释以获取有关错误的信息)
#include <stdio.h>
#include <stdlib.h>
#include "jstring.h"
int main()
{
char name[] = "Juan";
printf("The char 'a' is in the index %d \n\n", indexOf(name, 'a'));
return 0;
}
jstring.h
#include <string.h>
int indexOf(char haystack[], char needle)
{
int index = 0;
while(haystack[index] != '\0')
{
//Prints char by char untill the needle is found (for testing)
printf("%c\n", haystack[index]);
if(strcmp(haystack[index], needle) == 0) //Causes error (app strops working)
{
printf("Needle found!");
return index;
}
index++;
}
return -1;
}
如果我使用下一个代码,它就不起作用
if(haystack[index] == needle) //Is never true
{
printf("Needle found!");
return index;
}
知道名字是“Juan”的程序应该返回 2 作为字符“a”位置的索引。我不知道这段代码有什么问题,我已经习惯了指针,也许与此有关。
我搜索了很多有关比较字符的 StackOverflow 问题,但没有找到最终不使用 strcmp()
或与我的函数具有相似目标的问题。
最佳答案
首先你不能使用
if(strcmp(haystack[index], needle) == 0)
因为 needle
不是以 null
结尾的字符串。 haystack[index]
都不是。要在 strcmp
中使用 haystack[index]
,您必须使用 &haystack[index]
。
其次,您的代码使用简单的 ==
效果很好
int indexOf(char haystack[], char needle)
{
int index = 0;
while(haystack[index] != '\0')
{
//Prints char by char untill the needle is found (for testing)
printf("%c\n", haystack[index]);
if(haystack[index] == needle )
{
printf("Needle found!\n");
return index;
}
index++;
}
return -1;
}
int main()
{
char name[] = "Juan";
printf("The char 'a' is in the index %d \n\n", indexOf(name, 'a'));
return 0;
}
关于比较 C 中的字符会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33887366/