Monday, January 13, 2020

Printing Tokens - Hacker Rank Solution

Given a sentence, , print each word of the sentence in a new line.
Printing Tokens - Hacker Rank Solution
In the previous challenges, you have learnt how to input a string which has spaces using scanf function. Here, once you have taken the sentence as input, we need to iterate through the input, and keep printing each character one after the other unless you encounter a space. When a space is encountered, you know that a token is complete and space indicates the start of the next token after this. So, whenever there is a space, you need to move to a new line, so that you can start printing the next token. Look at the code given below.
#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;
}

6 comments:

Powered by Blogger.