定义一个字符型变量用关键字char,后面跟着变量名。程序中char c;表示在内存中开辟一个空间叫c,里面装的数据类型是字符型。
字符型变量占用内存空间是1字节(byte)。
注:char是character这个单词的缩写。
1 2 3 4 5 6 7 8 9 10 11 | /****************************************************************************** charVariable *******************************************************************************/ #include <iostream> using namespace std; int main(){ char c; //定义字符型变量c c='A'; //赋值变量c为’A’ cout<<c<<endl; //输出c的值 return 0; } |
字符处理函数:
isalpha(int c)
A-Z
或 a-z
)。#include <cctype>
或 #include <ctype.h>
c
是字母,返回非零值(通常是1);否则返回0。tolower(int c)
#include <cctype>
或 #include <ctype.h>
c
是大写字母,返回对应的小写字母;否则原样返回。toupper(int c)
#include <cctype>
或 #include <ctype.h>
c
是小写字母,返回对应的大写字母;否则原样返回。代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include <iostream> #include <cctype> // isalpha, tolower, toupper using namespace std; int main() { const int MAX_LEN = 100; char input[MAX_LEN]; cout << "请输入一个字符串(最多99字符):"; cin.getline(input, MAX_LEN); char lower[MAX_LEN], upper[MAX_LEN]; int i = 0; int totalCount = 0; // 总字符数 int letterCount = 0; // 字母数量 while (input[i] != '\0') { char ch = input[i]; lower[i] = tolower(ch); upper[i] = toupper(ch); if (isalpha(ch)) { letterCount++; } i++; } lower[i] = '\0'; upper[i] = '\0'; totalCount = i; cout << "原始字符串: " << input << endl; cout << "小写转换: " << lower << endl; cout << "大写转换: " << upper << endl; cout << "总字符数: " << totalCount << endl; cout << "其中是字母的有: " << letterCount << " 个" << endl; return 0; } |