1.字符与整数的联系--ASCII码表
char c = 'a' ;
cout << (int)c << endl;
int a = 66;
cout << (char)a << endl;
return 0;
特殊的ASCII值:‘A’-‘Z’:65~90 ‘a’-‘z’:97~122 ‘0’-‘9’:48~57
字符可以参与运算,运算时将其作为整数
int a = 'A' - 'B';
cout << a << endl;
判断字符与数字
char c;
int nums = 0, chars = 0;
while(cin >> c){
if(c >= '0' and c <= '9') nums++;
else if(c >= 'A' and c <= 'Z' or c >= 'a' and c <= 'z') chars++;
}
printf("nums:%d\nchars: %d\n",nums,chars);
return 0;
Acwing 772.只出现一次的字符
char str[100010];
int cnt[26];
int main()
{
cin >> str;
// for(int i=0;i<strlen(str);i++) cnt[str[i] - 'a']++ ;
// for(int i=0,len= strlen(str);i<len;i++) cnt[str[i] - 'a']++ ;
//还有一种做法就是直接不求长度
for(int i=0;str[i];i++) cnt[str[i] - 'a']++ ;
//是否有一个字符只出现了一次
// for(int i=0;i<strlen(str);i++)
// for(int i=0,len=strlen(str);i<len;i++)
for(int i=0;str[i];i++)
if(cnt[str[i] - 'a'] == 1)
{
cout << str[i] << endl;
return 0;
}
puts("no");
return 0;
}
Acwing 769.替换字符
char str[31];
cin >> str ;
char c;
cin >> c;
for(int i=0;str[i];i++)
{
if(str[i]== c) str[i]='#';
}
puts(str);
return 0;
2.标准库string:可变长的字符序列, 比字符数组更好用,需要引入头文件:#include <string>
string s1;
string s2 = s1;
string s3 = "java";
string s4(10,'c'); //s4:cccccccccc
return 0;
string的操作
//读入
string s1,s2;
cin >> s1 >> s2;
//读出
cout << s1 << ' ' << s2 << endl;
printf("%s\n",s1.c_str());
puts(s1.c_str()\n);
string s1,s2;
getline(cin,s1); //读入一整行,如果是cin的话,遇到空格就会停止了
cin >> s1 ;
cout << s1 << endl;
//string的empty和size操作 并规定s.size()<=-1
string s1,s2="abc";
cout << s1.empty() << endl; //1 空
cout << s2.empty() << endl; //0 非空
cout << s2.size() << endl; //3
//string对象赋值
string s3(10,'c'),s4;
s3 = s4 ; //得到两个空的字符串
//两个string对象相加
string s1 = "hello",s2 = "world\n";
string s3 = s1+s2;
s1= s1+s2;
cout << s3 << endl; //helloworld
cout << s1 << endl; //helloworld
//字面值和字符运算必须保证至少一边是string类型
string s1 = "abc";
string s2 = "def";
string s3 = s1 + "," + s2 ;
cout << s3 << endl; //abc,def 此时输出是合法的
string s4 = "abc" + "!"; //报错,因为两边都是字符串
处理string对象中的字符问题
//1.以字符数组处理
string s = "hello world!";
for(int i=0;i<s.size();i++)
{
cout << s[i] << endl;
}
//2.增强for循环
string s1 = "abcdef";
for(char c : s1) cout << c << endl;
//改变值
for(char &c : s1) c = 'a' ;
cout << s1 << endl;
return 0;