Printing Tokens in C - Hacker Rank Solution

Hello coders, today we will be solving Printing Tokens in C Hacker Rank Solution. Given a sentence, s, print each word of the sentence in a new line

Hello coders, today we will be solving Printing Tokens in C Hacker Rank Solution.

Printing Tokens in C - Hacker Rank Solution

Objective

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

Input Format

The first and only line contains a sentence, s.

Constraints

1 ≤ len(s) ≤ 1000

Output Format 

Print each word of the sentence in a new line.

Sample Input 0

This is C 

Sample Output 0

This
is
C

Explanation 0

In the given string, there are three words ["This", "is", "C"]. We have to print each of these words in a new line.

Sample Input 1

Learning C is fun

Sample Output 1

Learning
C
is
fun

Sample Input 2

How is that

Sample Output 2

How
is
that

Solution - Printing Tokens in C - Hacker Rank Solution 

#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;
}

Disclaimer: The above Problem (Printing Tokens in C) is generated by Hacker Rank but the Solution is provided by Sloth Coders.

A Sloth Who Code 

Sloth Coders 

Also Read:

Sloth Coders is a Learning Platform for Coders, Programmers and Developers to learn from the basics to advance of Coding of different langauges(python, Java, Javascript and many more).

Post a Comment