7월 23일(토) - 6단계(1152번)
6단계 - 1152번
1152번: 단어의 개수
첫 줄에 영어 대소문자와 공백으로 이루어진 문자열이 주어진다. 이 문자열의 길이는 1,000,000을 넘지 않는다. 단어는 공백 한 개로 구분되며, 공백이 연속해서 나오는 경우는 없다. 또한 문자열
www.acmicpc.net
문제점
1. (최초풀이) "The Curious Case of Benjamin Button" 을 입력시 6이 아닌 5가 출력됨
-> for 반복문의 word[i] != '\0'이기 때문에, 그 안의 조건문인 else if(word[i] == '\0') 가 실행될 수 없다는 것을 깨닫게 됨
-> 그렇기에 반복문 밖에서 count++을 넣는것으로 변경
2. (중간풀이 -1) "The last character is a balnk "을 입력시 6이 아닌 7이 출력됨
-> 반복문안에서 빈칸을 확인한 경우에만 count 값을 올리고, 마지막 단어의 개수를 count에 넣는 계산은 반복문밖에서 마지막에 count++하며 올리는 것으로 변경
-> 또한, 문자열의 가장 첫번째인 word[0]가 빈칸인 경우에는 count 값이 원래값보다 +1이 되므로, if문을 활용하여 count-- 하는 과정을 추가
3. (중간풀이 - 2) "The last character is a balnk "을 입력시 6이 아닌 7이 출력되는 오류가 여전히 발생함
-> <string.h>를 이용하여 len 변수를 선언 및 활용
-> 문자열의 가장 마지막인 word[len-1]이 공백인 경우에 count--를 하기 위해서 else if 조건문을 추가
4. 최종풀이
-> 문자열의 가장 마지막이 공백인 경우 count-- 하기 위한 조건문을 if 로 변경
/////////////////////////////////////////////////////////////////////
* 이전까지 word[i] != NULL 사용시 형식문제가 나오던것을 word[i] != '\0' 으로 바꾸며 해결
* word[len-1] == ' ' 부분에 c6385 에러가 발생함
-> 에러있지만 왜 정답판정? / 에러해결할 방법 알아볼 것
/////////////////////////////////////////////////////////////////////
최초풀이
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable: 4996)
#include <stdio.h>
int main(void)
{
int count = 0;
char word[1000000] = { 0, };
scanf("%[^\n]s", word);
for (int i = 0; word[i] != '\0'; i++)
{
if (word[i] == ' ')
{
count++;
}
else if (word[i] == '\0')
{
count++;
}
}
printf("%d", count);
return 0;
}
중간풀이 - 1
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable: 4996)
#include <stdio.h>
int main(void)
{
int count = 0;
char word[1000000] = { 0, };
scanf("%[^\n]s", word);
for (int i = 0; word[i] != '\0'; i++)
{
if (word[i] == ' ')
{
count++;
}
else
{
continue;
}
}
count++;
if (word[0] == ' ')
{
count--;
}
printf("%d", count);
return 0;
}
중간풀이 - 2
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable: 4996)
#include <stdio.h>
#include <string.h>
int main(void)
{
int count = 0;
char word[1000000] = { 0, };
scanf("%[^\n]s", word);
int len = strlen(word);
for (int i = 0; i<len; i++)
{
if (word[i] == ' ')
{
count++;
}
}
if (word[0] == ' ')
{
count--;
}
else if (word[len - 1] == ' ')
{
count--;
}
printf("%d", count+1);
return 0;
}
최종풀이
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable: 4996)
#include <stdio.h>
#include <string.h>
int main(void)
{
int count = 0;
char word[1000000] = { 0, };
scanf("%[^\n]s", word);
int len = strlen(word);
for (int i = 0; i<len; i++)
{
if (word[i] == ' ')
{
count++;
}
}
if (word[0] == ' ')
{
count--;
}
if (word[len - 1] == ' ')
{
count--;
}
printf("%d", count+1);
return 0;
}