This blog is under construction

Sunday 14 July 2013

C program to break sentence into words

Write a C program to print words in the given string.



  #include <stdio.h>
  #include <string.h>

  int main() {
        char str[512], word[256];
        int i = 0, j = 0;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(str, 512, stdin);
        str[strlen(str) - 1] = '\0';

        /* checking whether the input string is NULL */
        if (str[0] == '\0') {
                printf("Input string is NULL\n");
                return 0;
        }

        /* printing words in the given string */
        while (str[i] != '\0') {
                /* ' '  is the separator to split words */
                if (str[i] == ' ') {
                        word[j] = '\0';
                        printf("%s\n", word);
                        j = 0;
                } else {
                        word[j++] = str[i];
                }
                i++;
        }

        word[j] = '\0';

        /* printing last word in the input string */
        printf("%s\n", word);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:print the words in the input string
  print
  the
  words
  in
  the
  input
  string


1 comment:

  1. please help me how to sort the words in alphabetical order

    ReplyDelete