#include <stdio.h>
#include <string.h>
int main() {
char s[1000];
fgets(s, sizeof(s), stdin);
// Removing newline character from the input string
if (s[strlen(s) - 1] == '\n') {
s[strlen(s) - 1] = '\0';
}
// Tokenizing the input string
char *token = strtok(s, " ");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, " ");
}
return 0;
}
Let's go through the solution step by step:
We include the
In the main() function, we declare a character array s of size 1000 to store the input string.
We use the fgets() function to read the input string from the user. The sizeof(s) argument ensures that we read at most 1000 characters, including the newline character.
If the input string ends with a newline character (which is typically the case with fgets()), we replace it with a null character using s[strlen(s) - 1] = '\0'. This ensures that the string doesn't have a trailing newline character.
We declare a character pointer token to store the individual tokens as we tokenize the input string.
We use the strtok() function to tokenize the input string. The first call to strtok() uses s as the first argument, which represents the input string. The second argument " " is the delimiter, specifying that we want to split the string whenever a space character is encountered.
We use a while loop to iterate through the tokens until token becomes NULL. Inside the loop, we print each token using the printf() function, followed by a newline character.
After printing a token, we call strtok() again with NULL as the first argument to continue tokenizing the string. This allows us to retrieve the next token.
By providing the expected input and executing the code, you should see each token of the input string printed on a new line according to the problem statement on HackerRank.
This solution assumes valid input and does not perform extensive error handling for