How to count the number of words in a string with C

3 Answers

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 str[] = "c is a general purpose procedural programming language";
 
    printf("%d", count_words(str, " "));

    return 0;
}
 
    
    
/*
run:
    
8
    
*/

 



answered Jan 19, 2021 by avibootz
edited Nov 1, 2025 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
  
int count_words(char str[]) {
    int words_counter = (str[0] == '\0') ? 0 : 1;
 
    int i = 0;
    while (str[i] != '\0') {
        if (str[i]==' ' || str[i]=='\n' || str[i]=='\t') {
            words_counter++;
        }
        i++;
    }
     
    return words_counter;
}
  
  
int main(void)
{
    char str[] = "c is a general purpose procedural programming language";
 
    printf("%d", count_words(str));
 
    return 0;
}
 
    
    
/*
run:
    
8
    
*/

 



answered May 8, 2024 by avibootz
edited Nov 1, 2025 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
 
int count_words(char str[]) {
    int totalwords = 0;
    char last = ' ', *p;
     
    p = str;
    while (*p != '\0') {
        if (*p == ' ' && ( (last >= 'a' && last <= 'z') ||  (last >= 'A' && last <= 'Z') )) {
            totalwords++;
        }
        
        last = *p;
        p++;
    }
    
    if (last != ' ') totalwords++;
    
    return totalwords;
}
 
 
int main(void)
{
    char str[] = "C Programming    Developer Can        Develop an  OS";

    printf("%d", count_words(str));

    return 0;
}

   
   
/*
run:
   
7
   
*/

 



answered May 8, 2024 by avibootz
edited Nov 1, 2025 by avibootz

Related questions

...