C언어 공백 문자 처리
C언어에서 공백 문자를 효과적으로 처리하는 방법과 관련 함수들을 소개합니다.
공백 문자 상수
C언어에서 사용할 수 있는 공백 문자들과 그 ASCII 값입니다.
| 문자 | 이스케이프 시퀀스 | ASCII 값 | 설명 |
|---|---|---|---|
| 공백 | ' ' | 32 | 일반 공백 |
| 탭 | '\\t' | 9 | 수평 탭 |
| 개행 | '\\n' | 10 | 줄바꿈 |
| 수직 탭 | '\\v' | 11 | 수직 탭 |
| 폼피드 | '\\f' | 12 | 폼피드 |
| 캐리지 리턴 | '\\r' | 13 | 캐리지 리턴 |
공백 문자 판별 함수
isspace() 함수
#include <ctype.h>
#include <stdio.h>
int main() {
char ch;
printf("문자를 입력하세요: ");
ch = getchar();
if (isspace(ch)) {
printf("'%c'는 공백 문자입니다.\n", ch);
} else {
printf("'%c'는 공백 문자가 아닙니다.\n", ch);
}
return 0;
}개별 공백 문자 검사
#include <stdio.h>
void check_whitespace(char ch) {
printf("문자: '%c' (ASCII: %d)\n", ch, ch);
switch(ch) {
case ' ':
printf("-> 공백\n");
break;
case '\t':
printf("-> 탭\n");
break;
case '\n':
printf("-> 개행\n");
break;
case '\r':
printf("-> 캐리지 리턴\n");
break;
case '\f':
printf("-> 폼피드\n");
break;
case '\v':
printf("-> 수직 탭\n");
break;
default:
printf("-> 일반 문자\n");
}
}문자열에서 공백 문자 제거
앞뒤 공백 제거 (trim)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// 문자열 앞쪽 공백 제거
char* ltrim(char* str) {
while (isspace(*str)) {
str++;
}
return str;
}
// 문자열 뒤쪽 공백 제거
char* rtrim(char* str) {
char* end = str + strlen(str) - 1;
while (end > str && isspace(*end)) {
*end = '\0';
end--;
}
return str;
}
// 문자열 앞뒤 공백 제거
char* trim(char* str) {
return ltrim(rtrim(str));
}
int main() {
char text[] = " 안녕하세요 세계 ";
printf("원본: '%s'\n", text);
printf("trim 후: '%s'\n", trim(text));
return 0;
}모든 공백 문자 제거
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// 문자열에서 모든 공백 문자 제거
void remove_all_spaces(char* str) {
int i, j = 0;
for (i = 0; str[i]; i++) {
if (!isspace(str[i])) {
str[j++] = str[i];
}
}
str[j] = '\0';
}
int main() {
char text[] = "안녕 하세요\t세계\n";
printf("원본: '%s'\n", text);
remove_all_spaces(text);
printf("공백 제거 후: '%s'\n", text);
return 0;
}문자열 분할 (토큰화)
strtok() 함수 사용
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "사과 바나나\t오렌지\n포도";
char* token;
// 공백, 탭, 개행을 구분자로 사용
token = strtok(text, " \t\n");
while (token != NULL) {
printf("토큰: '%s'\n", token);
token = strtok(NULL, " \t\n");
}
return 0;
}수동 분할 함수
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void split_by_whitespace(char* str) {
int i = 0;
int start = 0;
int in_word = 0;
while (str[i]) {
if (!isspace(str[i])) {
if (!in_word) {
start = i;
in_word = 1;
}
} else {
if (in_word) {
// 단어 출력
printf("단어: '");
for (int j = start; j < i; j++) {
printf("%c", str[j]);
}
printf("'\n");
in_word = 0;
}
}
i++;
}
// 마지막 단어 처리
if (in_word) {
printf("단어: '");
for (int j = start; j < i; j++) {
printf("%c", str[j]);
}
printf("'\n");
}
}공백 문자 통계
#include <stdio.h>
#include <ctype.h>
void count_whitespace(char* str) {
int spaces = 0, tabs = 0, newlines = 0, others = 0;
int i = 0;
while (str[i]) {
if (isspace(str[i])) {
switch(str[i]) {
case ' ':
spaces++;
break;
case '\t':
tabs++;
break;
case '\n':
newlines++;
break;
default:
others++;
}
}
i++;
}
printf("공백: %d개\n", spaces);
printf("탭: %d개\n", tabs);
printf("개행: %d개\n", newlines);
printf("기타 공백: %d개\n", others);
}공백 문자 치환
#include <stdio.h>
#include <ctype.h>
// 모든 공백을 특정 문자로 치환
void replace_whitespace(char* str, char replacement) {
int i = 0;
while (str[i]) {
if (isspace(str[i])) {
str[i] = replacement;
}
i++;
}
}
// 특정 공백 문자만 치환
void replace_specific_whitespace(char* str, char target, char replacement) {
int i = 0;
while (str[i]) {
if (str[i] == target) {
str[i] = replacement;
}
i++;
}
}
int main() {
char text1[] = "안녕\t하세요\n세계";
char text2[] = "안녕\t하세요\n세계";
printf("원본: '%s'\n", text1);
replace_whitespace(text1, '_');
printf("모든 공백 치환: '%s'\n", text1);
replace_specific_whitespace(text2, '\t', '|');
printf("탭만 치환: '%s'\n", text2);
return 0;
}파일에서 공백 처리
#include <stdio.h>
#include <ctype.h>
void process_file_whitespace(const char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("파일을 열 수 없습니다.\n");
return;
}
char ch;
int line = 1, col = 1;
while ((ch = fgetc(file)) != EOF) {
if (isspace(ch)) {
switch(ch) {
case ' ':
printf("라인 %d, 열 %d: 공백\n", line, col);
break;
case '\t':
printf("라인 %d, 열 %d: 탭\n", line, col);
break;
case '\n':
printf("라인 %d, 열 %d: 개행\n", line, col);
line++;
col = 0;
break;
}
}
col++;
}
fclose(file);
}컴파일 및 실행
Windows (MinGW)
gcc -o whitespace_program program.c whitespace_program.exeLinux/macOS
gcc -o whitespace_program program.c ./whitespace_program주의사항
- 문자열 수정 시 배열 크기 확인 필요
- strtok() 함수는 원본 문자열을 수정함
- 포인터 사용 시 메모리 접근 주의
- 파일 처리 시 반드시 fclose() 호출
- 유니코드 문자는 별도 처리 필요