strtolower(), strtoupper()
대소문자를 변경하는 함수로 코딩 테스트에서 자주 등장한다
전달 받은 문자열을 모두 소문자, 혹은 모두 대문자로 바꾸는 함수이다
strtolower(), strtoupper() 구현
#include <stdio.h>
#include <assert.h>
int is_alpha(int c);
int to_upper(int c);
int to_lower(int c);
void string_toupper(char* str);
void string_tolower(char* str);
int main(void)
{
char str[15] = "Welcome to C";
printf("Is space alphabet?: %s\n", is_alpha(' ') ? "Yes" : "No");
printf("m in uppercase: %c\n", to_upper('m'));
printf("W in lowercase: %c\n", to_lower('W'));
printf("before string_toupper(str): %s\n", str);
string_toupper(str);
printf("after string_toupper(str): %s\n", str);
string_tolower(str);
printf("after string_tolower(str): %s\n", str);
return 0;
}
int is_alpha(int c)
{
return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
}
int to_upper(int c)
{
if (is_alpha(c)) {
return c & ~0x20;// 뺄셈연산보다 비트마스킹이 더 효율적
}
return c;
}
int to_lower(int c)
{
if (is_alpha(c)) {
return c | 0x20;
}
return c;
}
void string_toupper(char* str)
{
while (*str != '\0') {
*str = to_upper(*str);
++str;
}
}
void string_tolower(char* str)
{
while (*str != '\0') {
*str = to_lower(*str);
++str;
}
}
'C > [코드조선] C 핵심' 카테고리의 다른 글
[C] 문자열 정렬 (0) | 2024.02.10 |
---|---|
[C] strrev() (0) | 2024.02.10 |
[C] strcat(), strstr(), strtok() (0) | 2024.02.10 |
[C] strcpy() (0) | 2024.02.09 |
[C] strcmp() (0) | 2024.02.09 |