coder18s,blogspot.com

Powered by Blogger.

Printing Tokens in C HackerRank Solution

 TASK

Given a sentence, , print each word of the sentence in a new line.

Sample Input 

Learning C is fun

Sample Output 

Learning
C
is
fun

Sample Input 

How is that

Sample Output 

How
is
that
               PROGRAM CODE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *s;
    s = malloc(1024 * sizeof(char));
    scanf("%[^\n]", s);
    s = realloc(s, strlen(s) + 1);
    int len = strlen(s);
    for(int i = 0; i < len; i++) {
        if(s[i] == ' ') {
            printf("\n");
        }
        else {
            printf("%c", s[i]);
        }
    }
    free(s);
    return 0;
}