Reputation: 1533
Beginner question: I'm trying to make a char array comprising function, it should compare 2 arrays - pattern and text and return an index of the text that similar the most:
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;
}
the output is (instead of a blacnk char there is a '?' upside down-picture included:
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
Upvotes: 0
Views: 143
Reputation: 101
I did some changes to your code and it works now. you weren't comparing correctly the characters you needed to...
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;
}
Upvotes: 2