HackerRank Printing Tokens Solution in C

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

Input Format

The first and only line contains a sentence, .

Constraints

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

HackerRank Printing Tokens Solution in C (Sample-1)

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

int main() {
    char s[1000];

    // Read the full line (including spaces)
    fgets(s, sizeof(s), stdin);

    // Use strtok to split tokens by space and newline
    char *token = strtok(s, " \n");

    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, " \n");
    }

    return 0;
}

HackerRank Printing Tokens Solution in C (Sample-2)

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

int main() {
    char str[1000];
    fgets(str, sizeof(str), stdin);

    char *token = strtok(str, " \n");

    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, " \n");
    }

    return 0;
}

HackerRank Printing Tokens Solution in C (Sample-3)

#include <stdio.h>

int main() {
    char str[1000];
    fgets(str, sizeof(str), stdin);

    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == ' ' || str[i] == '\n')
            printf("\n");
        else
            printf("%c", str[i]);
    }

    return 0;
}


Post a Comment

0 Comments