
C++ isupper, islower, isdigit - 문자 대소문자, 숫자 판별
Notepad96
·2020. 11. 20. 06:07
1. isdigit, isupper, islower, isspace
문자열에서 대문자를 소문자로, 소문자를 대문자로 바꾸어주고 싶다거나 숫자인 경우 특정 행동을 해주고 싶을 경우가 있다.
isdigit, isupper, islower, isspace 함수들은 각각 숫자인지 판별하거나 문자가 대문자인지, 소문자인지 공백인지 등 판별하여 준다.
해당 함수들은 cctype 라이브러리의 포함되어 있다.
2. 코 드
환경 : Visual studio 2019
#include <iostream>
#include <string>
#include <cctype> // or <ctype.h>
using namespace std;
int main() {
string s = "34rewRE d3fs5R f0z";
cout << "문자열 s = " << s << "\n";
for (int i = 0; i < s.size(); i++) {
cout << s[i] << " 는 ";
if (isdigit(s[i])) {
cout << "숫자 입니다.";
}
else if (isspace(s[i])) {
cout << "공백 입니다.";
}
else if (isupper(s[i])) {
cout << "대문자 입니다.";
s[i] = tolower(s[i]); // 소문자 변환
//s[i] += 32; // 소문자 변환
}
else if (islower(s[i])) {
cout << "소문자 입니다.";
s[i] = toupper(s[i]); // 대문자 변환
//s[i] -= 32; // 대문자 변환
}
else if (isalpha(s[i])) {
cout << "알파벳 입니다.";
}
cout << "\n";
}
cout << "문자열 s = " << s << "\n";
return 0;
}

- 문자열을 루프를 돌며 각 문자에 대하여 검사한다.
isdigit : 숫자인지 판별
isspace : 공백인지 판별
isupper : 대문자인지 판별
islower : 소문자인지 판별
isalpha : 알파벳인지 판별
이처럼 각 함수들을 사용하면 해당 문자가 어떠한 것인지 판별해낼 수 있다.
- 대문자에서 소문자로 바꾸어주기 위해서는 tolower함수를 사용하거나 32를 더함으로써 바꾸어줄수 있다.
32를 더함은 아스키 코드상 10진수 값에 차이가 그러해서다.
'A' = 65
'a' = 97
소문자에서 대문자로 바꾸어주기 위해서 toupper 함수를 사용할 수 있으며 마찬가지로 반대로 32를 빼줌으로서 소문자에서 대문자로 바꾸어줄 수 있다.
3. 참 조
isupper - C++ Reference
function isupper Check if character is uppercase letter Checks if parameter c is an uppercase alphabetic letter. Notice that what is considered a letter may depend on the locale being used; In the default "C" locale, an uppercase letter is any of:
www.cplusplus.com
'C++ > STL' 카테고리의 다른 글
C++ String to int, int to String - 문자열 숫자 형변환 (0) | 2020.11.20 |
---|---|
C++ ratio 분수 계산 - 분자, 분모 저장 (0) | 2020.11.20 |
C++ min, max 함수 (0) | 2020.11.19 |
C++ time, clock 시간 측정, 현재 시간 구하기 (0) | 2020.11.18 |
C++ 원소 삭제하기 remove (0) | 2020.11.18 |