Printing Tokens in C - Hacker Rank Solution
Printing Tokens in C - Hacker Rank Solution |
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
Solution :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | //Printing Tokens in C - Hacker Rank Solution #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; } |
Disclaimer :-
the above whole problem statement is given by hackerrank.com but the solution is generated by the codeworld19 authority if any of the query regarding this post or website fill the following contact form thank you.
#include
#include
#include
#include
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.
while(*(s)!='\0'){
if(*(s)!=' ')
printf("%c",*(s));
else
printf("\n");
s++;
}
return 0;
}