处理string对象的字符常用方法如下:
isalnum():判断字符是否是字母或数字;
isalpha():判断字符是否是字母;
iscntrl():判断字符是否是控制字符;
isdigit():判断字符是否是数字;
isgraph():判断字符是否是可打印的非空格字符;
ispunct():判断字符是否是标点符号;
isspace():判断字符是否是空白字符;
isupper():判断字符是否是大写字母;
isxdigit():判断字符是否是十六进制数;
toupper():转换为大写字母;
tolower():转换为小写字母。
实例:
StringDealChar.cpp
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
int main() {
string s("Hello, World!123\n");
//字母或数字的个数
string::size_type alnumCount = 0;
//字母的个数
string::size_type alphaCount = 0;
//控制字符的个数
string::size_type cntrlCount = 0;
//数字的个数
string::size_type digitCount = 0;
//可打印的非空格字符的个数
string::size_type graphCount = 0;
//标点符号的个数
string::size_type punctCount = 0;
//空白字符的个数
string::size_type spaceCount = 0;
//大写字母的个数
string::size_type upperCount = 0;
//十六进制数的个数
string::size_type xdigitCount = 0;
for (string::size_type i = 0; i < s.size(); i++) {
//判断字符是否是字母或数字
if (isalnum(s[i])) {
alnumCount++;
}
//判断字符是否是字母
if (isalpha(s[i])) {
alphaCount++;
}
//判断字符是否是控制字符
if (iscntrl(s[i])) {
cntrlCount++;
}
//判断字符是否是数字
if (isdigit(s[i])) {
digitCount++;
}
//判断字符是否是可打印的非空格字符
if (isgraph(s[i])) {
graphCount++;
}
//判断字符是否是标点符号
if (ispunct(s[i])) {
punctCount++;
}
//判断字符是否是空白字符
if (isspace(s[i])) {
spaceCount++;
}
//判断字符是否是大写字母
if (isupper(s[i])) {
upperCount++;
}
//判断字符是否是十六进制数
if (isxdigit(s[i])) {
xdigitCount++;
}
}
cout << s << endl;
cout << "alnumCount: " << alnumCount << endl;
cout << "alphaCount: " << alphaCount << endl;
cout << "cntrlCount: " << cntrlCount << endl;
cout << "digitCount: " << digitCount << endl;
cout << "graphCount: " << graphCount << endl;
cout << "punctCount: " << punctCount << endl;
cout << "spaceCount: " << spaceCount << endl;
cout << "upperCount: " << upperCount << endl;
cout << "xdigitCount: " << xdigitCount << endl;
//全部转换为大写字母
for (string::size_type i = 0; i < s.size(); i++) {
s[i] = toupper(s[i]);
}
cout << s << endl;
//全部转换为小写字母
for (string::size_type i = 0; i < s.size(); i++) {
s[i] = tolower(s[i]);
}
cout << s << endl;
system("pause");
return 0;
}
联系客服