Header Ad

HackerRank Printing Tokens problem solution in C programming

In this HackerRank Printing Tokens problem solution in C programming, Given a sentence, s, print each word of the sentence in a new line.

HackerRank Printing Tokens problem solution in C programming


Problem solution in C programming.

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

int main() {

    char *s;
    s = malloc(1024 * sizeof(char));
    scanf("%[^\n]", s);
    s = realloc(s, strlen(s) + 1);
    for (char *c = s; *c != NULL; c++) {
    if (*c == ' ') {
        *c = '\n';
    }
}
printf("%s", s);
    return 0;
}

Explanation

Here first of all in the main function, we declare a character variable s and then we use the malloc function to allocate the 1024 size of memory to the s variable. and then we scan the values given by the user or you can say that we scan the complete paragraph and then we print each word in the new line using the for a loop.



Post a Comment

0 Comments