Printing Tokens | HackerRank
Given a sentence, print each word in a new line.
www.hackerrank.com
<문제>

input으로 한 문장이 입력되면 공백 단위로 단어를 나누고 각 단어를 한 줄에 하나 출력한다.
<코드>
#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);
//my logic to print the tokens of the sentence
for(int i = 0; i < strlen(s) ; i++)
{
if(s[i] == ' ')
printf("\n");
else
printf("%c",s[i]);
}
return 0;
}
<풀이>
이번 문제는 token이 아니라 단순하게 문자열을 한 글자씩 살펴보면서 공백문자이면 줄바꿈 문자로 바꾸어 출력하고, 공백문자가 아니면 해당 문자를 그냥 출력하도록 하면 풀릴 것 같았다. scanf()를 통해 문자를 입력받고 s에 저장하고 s를 realloc()을 통해 입력받은 길이만큼 메모리 할당을 해주었다. 그런 뒤 for문을 돌면서 s[i]의 문자가 공백인지 아닌지 조사하여 공백이면 줄바꿈 문자를 출력하게 하고 아니면 s[i]를 그대로 출력하도록 해 문제를 풀 수 있었다.
<실행결과>

'c언어 스터디 > HackerRank' 카테고리의 다른 글
| [HackerRank] Tree: Lowest Common Ancestor (0) | 2021.11.21 |
|---|---|
| [HackerRank] Equal Stacks (0) | 2021.11.07 |
| [HackerRank] Tree: Inorder Traversal (0) | 2021.10.10 |
| [hackerrank] Students Marks Sum (0) | 2021.10.10 |
| [HackerRank] Bitwise Operators (0) | 2021.10.02 |