×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to read a string and print the length of the each word

In this program, we will learn how to count length of each word in a string in C language?

There are many string manipulation programs and string user defined functions, this is an another program in which we will learn to count the length of each word in given string.

In this exercise (C program) we will read a string, like "Hi there how are you?" and it will print the word length of each word like 2, 5, 3, 3, 4.

Input
Hi there how are you?Output
2, 5, 3, 3, 4

Program to count length of each word in a string in C

#include <stdio.h>
#define MAX_WORDS 10

int main() {
  char text[100] = {0};      // to store string
  int cnt[MAX_WORDS] = {0};  // to store length of the words
  int len = 0, i = 0, j = 0;

  // read string
  printf("Enter a string: ");
  scanf("%[^\n]s", text);  // to read string with spaces

  while (1) {
    if (text[i] == ' ' || text[i] == '\0') {
      // check NULL
      if (text[i] == '\0') {
        if (len > 0) {
          cnt[j++] = len;
          len = 0;
        }
        break;  // terminate the loop
      }
      cnt[j++] = len;
      len = 0;
    } else {
      len++;
    }
    i++;
  }

  printf("Words length:\n");
  for (i = 0; i < j; i++) {
    printf("%d, ", cnt[i]);
  }
  printf("\b\b \n");  // to remove last comma

  return 0;
}

Output

Enter a string: Hi there how are you?
Words length:
2, 5, 3, 3, 4

C String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.