Hackerrank solution- Printing Tokens:
Welcome back Guys!!
In this post we will solve Printing Tokens Hackerrank problem.
It is a medium level problem using concept of Character Array ...
The soultion code For the Printing Tokens hackerrank Problem:
Problem statement for Printing Tokens hackerrank Problem:
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
The soultion code For the Printing Tokens hackerrank Problem:
The logic For this problem is easy just using loop analysis the character if its a space character replace it with new line character rest keep the characters as it is...
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
char *s;
int i;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s); // or you can use gets or fgets
s = realloc(s, strlen(s) + 1);
//Write your logic to print the tokens of the sentence here.
for(i=0;i<strlen(s);i++)
{
if(s[i]==' ') // replacing the space character with new line char.
{
printf("\n");
}
else {
printf("%c",s[i]);
}
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
char *s;
int i;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s); // or you can use gets or fgets
s = realloc(s, strlen(s) + 1);
//Write your logic to print the tokens of the sentence here.
for(i=0;i<strlen(s);i++)
{
if(s[i]==' ') // replacing the space character with new line char.
{
printf("\n");
}
else {
printf("%c",s[i]);
}
}
return 0;
}
Please read the code and analysis the code properly.
Feel free to share your thoughts and doubts in the comment section below.
See you next time.
1 Comments
Printing Tokens in C – Hacker Rank Solution
ReplyDeletehttps://www.codeworld19.com/printing-tokens-in-c-hacker-rank-solution/