cctype
是 C++ 標準庫中的一個字符處理函數(shù)庫,它提供了一系列用于字符分類和轉(zhuǎn)換的函數(shù)。這些函數(shù)在 iostream
、fstream
、string
等頭文件中都有定義。下面是一些常用 cctype
庫函數(shù)的使用示例:
isdigit
, isalpha
, isupper
, islower
, isspace
等函數(shù)可以用于判斷字符的類型。
#include <iostream>
#include <cctype>
int main() {
char ch = 'A';
if (isupper(ch)) {
std::cout << ch << " 是大寫字母" << std::endl;
} else {
std::cout << ch << " 不是大寫字母" << std::endl;
}
return 0;
}
toupper
, tolower
函數(shù)可以用于將字符轉(zhuǎn)換為大寫或小寫。
#include <iostream>
#include <cctype>
int main() {
char ch = 'a';
if (isupper(ch)) {
ch = tolower(ch);
} else {
ch = toupper(ch);
}
std::cout << ch << std::endl; // 輸出 'a' 或 'A',取決于原始字符的大小寫
return 0;
}
對于字符串,cctype
庫提供了一些批量處理函數(shù),如 isalpha
, isdigit
, isspace
等的字符串版本 isalpha(const std::string& s)
, isdigit(const std::string& s)
, isspace(const std::string& s)
。
#include <iostream>
#include <string>
#include <cctype>
int main() {
std::string str = "Hello, World!";
for (char ch : str) {
if (isalpha(ch)) {
std::cout << ch << " 是字母" << std::endl;
} else if (isdigit(ch)) {
std::cout << ch << " 是數(shù)字" << std::endl;
} else if (isspace(ch)) {
std::cout << ch << " 是空格" << std::endl;
}
}
return 0;
}
cctype
庫還提供了其他一些有用的函數(shù),如 tolower(int ch)
(將整數(shù)轉(zhuǎn)換為小寫字符)、toupper(int ch)
(將整數(shù)轉(zhuǎn)換為大寫字符)、swapcase(int ch)
(切換字符的大小寫)等。
注意:在使用這些函數(shù)時,請確保傳入的參數(shù)是有效的字符或整數(shù)。對于非字母和非數(shù)字的字符,isdigit
, isalpha
等函數(shù)可能會產(chǎn)生未定義的行為。