Printing Tokens - Hacker Rank Solution
In the previous challenges, you have learnt how to input a string which has spaces using scanf function. Here, once you have taken the sentence as input, we need to iterate through the input, and keep printing each character one after the other unless you encounter a space. When a space is encountered, you know that a token is complete and space indicates the start of the next token after this. So, whenever there is a space, you need to move to a new line, so that you can start printing the next token. Look at the code given below.
#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;
}
ok it was helpful
ReplyDeleteok it was helpful
ReplyDeleteokay it was helpful
ReplyDeleteplease explain this code
ReplyDeleteok
ReplyDeletePrinting Tokens in C – Hacker Rank Solution
ReplyDeletehttps://www.codeworld19.com/printing-tokens-in-c-hacker-rank-solution/