This blog is under construction

Sunday 14 July 2013

C program to print words in the string starting with the given character

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


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

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

        i = j = k = 0;

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

        /* get the input character from the user */
        printf("Enter your input character:");
        ch = getchar();

        /* print the words starting with given i/p character */
        printf("Words starting with %c:\n", ch);
        while (str[i] != '\0') {
                if (str[i] == ' ') {
                        /* checks whether words starts with i/o char */
                        if (word[0] == ch) {
                                word[j] = '\0';
                                printf("%s\n", word);
                        }
                        strcpy(word, "\0");
                        j = 0;
                } else {
                        /* extract words from string */
                        word[j++] = str[i];
                }
                i++;
        }
        /* checking last word in the string */
        if (word[0] == ch) {
                word[j] = '\0';
                printf("%s\n", word);
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:Hello.. How Are You? Hmm!!    
  Enter your input character:H
  Words starting with H:
  Hello..
  How
  Hmm!!


No comments:

Post a Comment