This page looks best with JavaScript enabled

HackerRank - Printing Tokens

 ·  ☕ 2 min read  ·  ✍️ devoalda

Introduction

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

Input and Output Format

1
2
3
4
5
6
7
# Input:
This is C

# Output:
This
is
C

{: file="Input and Output” }

Process

This was a pretty simple challenge. Completing the code, I’ve added a for loop to print each character at a time, scanning for any blank spaces and “replacing” that with a newline escape character \n.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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);
    //Write your logic to print the tokens of the sentence here.
    for (int i = 0;i <strlen(s); i++){
        //if(s[i] != ' '){
        //    printf("%c", s[i]);
        //}
        //else{
        //    printf("\n");
        //}
        (s[i] != ' ') ? printf("%c", s[i]) : printf("\n");
    }
    return 0;

{: file="Printing Tokens.c” }

Afterthoughts

Looping through each character in the string, a check is done to check for blankspaces and replacing them with a newline character.

I did it using an ordinary for loop but translated that same loop to a ternery operator for elegance. I really like the use of ternery operators in C.

This challenge earned me 20 points!

Share on

Devoalda
WRITTEN BY
devoalda
Technophile