In this tutorial, we are going to solve the HackerRank printing tokens problem in c programming with practical program code example and step-by-step explanation. in this problem, we need to take a sentence as input that length will always be less than 1000 characters and we need to print each word of the sentence in a new line.
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;
}
Second solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *p;
p = malloc(1024 * sizeof(char));
scanf("%[^\n]", p);
p = realloc(s, strlen(p) + 1);
int len = strlen(p);
for(int i = 0; i < len; i++) {
if(p[i] == ' ') {
printf("\n");
}
else {
printf("%c", p[i]);
}
}
free(p);
return 0;
}