입력 코드
#include <stdio.h>
#include <string.h>
#include <ctype.h>
main() {
char s[1000000];
int i, len;
int num = 0, space = 0;
gets(s);
len = strlen(s);
for (i = 0; i < len; i++) {
if (s[i] == ' ')
space++;
}
num = space + 1;
if (len == space) {
num = 0;
printf("%d", num);
}
else {
if (isspace(s[0]))
num--;
if (isspace(s[len - 1]))
num--;
printf("%d", num);
}
}
코드 설명
#배열 #공백 #조건문 #논리연산자 #fgets #isspace
#include <stdio.h>
#include <string.h>
main() {
char s[1000000];
int i;
scanf("%s", s);
int count = 0;
for (i = 0; i < strlen(s); i++) {
if (s[i] == " ") {
if (i == 0 | i == strlen(s))
count = count;
else
count++;
}
}
printf("%d\n", count);
}
처음에는 문자 앞뒤의 공백을 i=0 이거나 i==strlen(s)으로 작성했는데 제대로 결과가 안 나왔다.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
main() {
char s[1000000];
int i, len;
int num = 0, space = 0;
gets(s);
len = strlen(s);
for (i = 0; i < len; i++) {
if (s[i] == ' ')
space++;
}
num = space + 1;
if (len == space) {
num = 0;
printf("%d", num);
}
else {
if (isspace(s[0]))
num--;
if (isspace(s[len - 1]))
num--;
printf("%d", num);
}
}
그래서 다른 풀이를 참고해서 gets, isspace를 이용해서 다시 작성했다.
여러 자료들을 찾아봤지만 사실 아직도 이 두 함수의 사용법을 정확하게 모르겠다.
whitespace를 판별해주는 함수 isspace
※ whitespace에 해당하는 문자 ※
문자 | 뜻 |
' ' | 스페이스, 공백 |
'\n' | 라인피드 |
'\t' | 수평 탭 |
'\v' | 수직 탭 |
'\f' | 폼 피드 |
'\r' | 캐리지리턴 |
▶헤더파일 : #include <ctype.h>
isspace 외에도 isalpha, isdigit, isalnum 등의 판별 함수들이 있음
▶함수 프로토타입 : int isspace (int c);
int c : 판별할 문자
▶리턴값 : whitespace에 해당하면 0이 아닌 값을 리턴하고, whitespace가 아니면 0을 리턴
입력함수 gets
▶헤더파일 : #include <stdio.h>
▶함수 프로토타입 : gets(str);
str : 입력할 문자형 배열
※ 문자열만 입력받을 수 있고, 개행을 기준으로 입력받는다.
※ 문자열을 입력받아 함수의 인자로 명시한 주소의 메모리에 저장한 뒤 입출력 버퍼가 비어있는지 확인하고 비어있다면 문자 혹은 문자열을 입력받아 입출력 버퍼에 저장한다.
※ 참고 ※
egloos.zum.com/lechocolat/v/441439
↓↓↓ 참고한 사이트
m.blog.naver.com/tipsware/221286903892
문제 출처
'C' 카테고리의 다른 글
#33. [백준_C언어] 5622 : 다이얼 (0) | 2021.01.16 |
---|---|
#32. [백준_C언어] 2908 : 상수 (0) | 2021.01.16 |
#30. [백준_C언어] 1157 : 단어 공부 (0) | 2021.01.14 |
#29. [백준_C언어] 10809 : 알파벳 찾기 (0) | 2021.01.14 |
#28. [백준_C언어] 4673 : 셀프 넘버 (1) | 2021.01.13 |