初学者问题: 我正在尝试创建一个包含函数的char数组,它应该比较2个数组 - 模式和文本,并返回最相似的文本的索引:
int main(int argc, const char * argv[])
{
int answer =0;
answer = match("viva","vviaaa");
printf("%d",answer);
return 0;
}
int match(char pattern[],char text[]) {
int i,t,counter=0,topCount=0,topIndex=0;
for (t=0;pattern[t]!= '\0'; t++) {
counter=0;
for (i=t; text[i]!='\0'; i++) {
printf("is %c = %c ?\n",pattern[i],text[i]);
if (pattern[i] == text[i]) {
counter++;
printf("yes\n");
}
if (pattern[i] =='\0') {
break;
}
}
if (counter>topCount) {
printf("%d > %d at index t: %d\n",counter,topCount,t);
topCount = counter;
topIndex = t;
}
}
return topIndex;
}
输出是(而不是blacnk char,有一个'?'倒置图片包括:
is v = v ?
yes
is i = v ?
is v = i ?
is a = a ?
yes
is � = a ?
2 > 0 at index t: 0
is i = v ?
is v = i ?
is a = a ?
yes
is � = a ?
is v = i ?
is a = a ?
yes
is � = a ?
is a = a ?
yes
is � = a ?
0Program ended with exit code: 0
答案 0 :(得分:2)
我对您的代码进行了一些更改,现在可以正常运行了。你没有正确比较你需要的角色......
int match(char pattern[],char text[]);
int main(int argc, const char * argv[])
{
int answer = 0;
answer = match("viva","vviaaa");
printf("%d\n",answer);
return 0;
}
int match(char pattern[],char text[])
{
int i,j,k,counter=0,topCount=0,topIndex=0;
for (i=0; text[i]!= '\0'; i++)
{
counter = 0;
for (j=0,k=i; pattern[j]!='\0' && text[k]!='\0' && pattern[j] == text[k]; j++,k++,counter++);
if(counter > topCount)
{
topCount = counter;
topIndex = i;
}
}
return topIndex;
}