Tech Blog/C and C++
C언어 - 문자와 문자열 (실습포함)
EXPRESSIONS HAVE POWER
2021. 6. 10. 12:21
문자
#include <stdio.h>
int main()
{
char c = 'A';
printf("%c\n", c);
}
실행결과
A
문자열 (영어)
#include <stdio.h>
int main()
{
char str[7] = "coding";
printf("%s\n", str);
return 0;
}
실행결과
coding
문자열 끝에는 '끝'을 의미하는 NULL문자 '\0' 이 포함되어야 함.
[c][o][d][i][n][g][\0]
문자열 (한글)
#include <stdio.h>
int main(){
char kor[] = "나도코딩";
printf("%s\n", kor);
printf("%lu\n", sizeof(kor));
return 0;
}
실행결과
윈도우 기준
9
맥북 기준
13
맥북 기준
char 크기 1 byte
영어 1글자 1 byte
한글 1글자 3 byte
윈도우 기준
char 크기 1 byte
영어 1글자 1 byte
한글 1글자 2 byte
결론 -> 문자열 출력시 사이즈 크기를 1개 '\0' 더 주어야 한다.
크기 [] 비어있게 주면 다 커버칠 수 있다!
실습
#include <stdio.h>
#include <string.h>
int mystrcmp(char s[], char t[]); // mystrcmp 함수 선언
int main(void) {
// 변수 선언
char s[100];
char t[100];
int i = 0;
int j = 0;
int result;
printf("사전 순위를 비교할 첫 번째 단어를 입력하세요: ");
while ((s[i++] = getchar()) != '\n'); // null 문장
s[--i] = '\0';
printf("사전 순위를 비교할 두 번째 단어를 입력하세요: ");
while ((t[j++] = getchar()) != '\n'); // null 문장
t[--j] = '\0';
result = mystrcmp(s, t); // mystrcmp 함수 콜
printf("%d\n", result);
if (result == 1)
printf("두 번째 단어가 사전에 먼저 나옵니다.\n");
if (result == 0)
printf("두 단어가 같습니다.\n");
if (result == -1)
printf("첫 번째 단어가 사전에 먼저 나옵니다.\n");
return 0;
}
int mystrcmp(char s[], char t[])
{
int result = 0;
int i;
int cmp_len = strlen(s) < strlen(t) ? strlen(t) : strlen(s);
for (i = 0; i <= cmp_len; i++)
{
if (s[i] < t[i])
{
result = -1;
break;
}
else if (s[i] > t[i])
{
result = 1;
break;
}
else
result = 0;
}
return result;
}
현재 상황 : 중간에 ?의 역할이 뭔지 모르겠음.