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

式の部分は、シーケンスを表すために使用されるオブジェクトです。宣言部分は、シーケンスの基本要素にアクセスするために使用される変数を定義する役割を果たします。各反復で、宣言部分の変数は、式部分の次の要素の値に初期化されます。
例えば:

	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