C/C++ handles characters in a string

Header file #include <cctype>
Insert picture description here
code example:

#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;
}

The for loop traversal is similar to the for in the foreach statement in C#

	for(declaration : expression)
		statement

The expression part is an object used to represent a sequence. The declaration part is responsible for defining a variable that will be used to access the basic elements in the sequence. In each iteration, the variable in the declaration part is initialized to the value of the next element in the expression part.
E.g:

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

If you want to modify the characters in str at the same time, use quotes:

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

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/115320049