I have a program that needs to count the number of first words in an array finalArr[].
To do this, I separately write the first word to an array distArr[]. Then I compare the elements of the finalArr[] array with the elements of the distArr[] array. But final result is incorrect. For example, I have string "qwe qwe qwe" in finalArr[], and correct result must be "3".
#include <stdio.h>
#include <string.h>
void main(void)
{
char finalArr[100];
char src;
int i = 0;
printf("Enter a string: ");
// fill the array
while ((src = getchar()) != '\n' && i < 99)
{
finalArr[i] = src;
i++;
}
finalArr[i] = '\0';
printf("Result is: %s\n", finalArr); // output array
// writing first word to distArr[]
char distArr[100];
int j = 0;
for (j = 0; j < strlen(finalArr); j++)
{
distArr[j] = finalArr[j];
if (finalArr[j] == ' ')
{
break;
}
}
distArr[j] = '\0';
printf("Dist array: %s\n", distArr);
printf("%c", distArr[0]);
// Compare the first word with all elements of the array finalArr[]
int count = 0;
int d;
for (int k = 0; k < strlen(finalArr); k++) {
if (finalArr[k] == ' ') {
k++;
}
for(int d = k; d < strlen(distArr); d++) {
if (distArr[d] == finalArr[d]) {
count++;
}
}
}
printf("Count: %d", count);
}
preferably, use one-dimensional arrays without strtok
>Solution :
Something like this could work:
#include <stdio.h>
#include <string.h>
int main() {
const char delim [] = " ";
char finalArr [] = "qwe qwe qwe";
char distArr [] = "qwe";
int count = 0;
char *ptr = strtok(finalArr, delim);
while(ptr != NULL)
{
if (!strcmp(ptr,distArr))
count++; //strings match
ptr = strtok(NULL, delim);
}
printf("Result:%d",count);
return 0;
}
This outputs:
Result:3