How to check if two strings have the same number of words in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
 
int count_words(char str[], char *delimiter) {
    if (str == "") {
        return 0;
    }

    char *word = strtok(str, delimiter);
    
    int count = 0;
    while (word != NULL) {
        count++;
        word = strtok(NULL, delimiter);
    }
    
    return count;
}
 
 
int main(void)
{
    char str1[] = "c is a general purpose procedural programming language";
    int count1 = count_words(str1, " ");

    char str2[] = "created in 1970s by Dennis Ritchie widely used";
    int count2 = count_words(str2, " ");
    
    printf("%s", count2 == count2 ? "yes" : "no");
}

   
   
/*
run:
   
yes
   
*/

 



answered May 8, 2024 by avibootz
...