C/C++处理字符串中的字符

头文件#include <cctype>
在这里插入图片描述
代码示例:

#include <cctype>
#include <iostream>
using namespace std;

int main() {
    
    
    string str = "012abcxyzABCXYZ \n\t~`!@#$%^&*()_+{}:\"|<>?[]\\;',./'";
    cout << "\tisalnum"
         << "\tisalpha"
         << "\tislower"
         << "\tisupper"
         << "\tisdigit"
         << "\tiscntrl"
         << "\tisgraph"
         << "\tisprint"
         << "\tispunct"
         << "\tisspace"
         << "\tisxdigit";
    cout << endl;

    for (int i = 0; i < str.size(); i++) {
    
    
        if (str[i] == '\t')
            cout << "\\t\t";
        else if (str[i] == '\n')
            cout << "\\n\t";
        else
            cout << str[i] << "\t";
        cout << isalnum(str[i]) << "\t";  // 当str[i]是字母或数字时为真
        cout << isalpha(str[i]) << "\t";  // 当str[i]是字母时为真
        cout << islower(str[i]) << "\t";  // 当str[i]是小写字母时为真
        cout << isupper(str[i]) << "\t";  // 当str[i]是大写字母时为真
        cout << isdigit(str[i]) << "\t";  // 当str[i]是数字时为真
        cout << iscntrl(str[i]) << "\t";  // 当str[i]是控制字符时为真
        cout << isgraph(str[i]) << "\t";  // 当str[i]不是空格但可打印时为真
        cout << isprint(str[i]) << "\t";  // 当str[i]是可打印字符(包括空格)
        cout << ispunct(str[i]) << "\t";  // 当str[i]是标点符号时为真
        cout << isspace(str[i]) << "\t";  // 当str[i]是空白时为真

        cout << isxdigit(str[i]) << "\t";  // 当str[i]是16进制数字时为真

        cout << endl;
    }

    for (int i = 0; i < str.size(); i++)
        str[i] = tolower(str[i]);  // 当str[i]是大写字母输出为小写
    cout << str << endl;
    for (int i = 0; i < str.size(); i++)
        str[i] = toupper(str[i]);  // 当str[i]是小写字母输出为大写
    cout << str << endl;
    system("pause");
    return 0;
}

for循环遍历类似于C#中foreach语句的for

	for(declaration : expression)
		statement

其中expression部分是一个对象,用于表示一个序列。declaration部分负责定义一个变量,该变量将被用于访问序列中的基础元素。每次迭代,declaration部分的变量会被初始化为expression部分的下一个元素值。
例如:

	for (auto c : str)  // 对str中的每个字符
		cout << c;
	cout << endl;

如果同时要修改str中的字符,则使用引用:

    for (auto &c : str) c = toupper(c);
    cout << str << endl;

猜你喜欢

转载自blog.csdn.net/qq_45349225/article/details/115320049
今日推荐