3.2 处理string对象中的字符
主要概念
- 一些常用 的string处理函数:
函数名 | 作用 |
---|---|
isalnum(c) | 当c是字母或数字时为真 |
isalpha(c) | 当c是字母时为真 |
islower(c) | 当c是小写字母时为真 |
isupper(c) | 当c是大写字母时为真 |
iscntrl(c) | 当c是控制字符时为真 |
isdigit(c) | 当c是数字时为真 |
isxdigit(c) | 当c是十六进制数字时为真 |
isgraph(c) | 当c不是空格但可以打印时为真 |
isprint(c) | 当c是可打印字符时为真(即c是空格或c具有可视形式) |
ispunct(c) | 当c是标点符号时为真 |
isspace(c) | 当c是空白时为真(即c是空格、横向或纵向制表符、回车符、换行符、进纸符的一种) |
tolower(c) | 当c是大写字母时输出对应的小写字母,否则返回原值 |
toupper(c) | 当c是小写字母时输出对应的大写字母,否则返回原值 |
- string值可以使用下标取值,使用时要注意下标范围,不能超出
- 使用基于范围的for语句:
for(declaration:expression)
statement
练习
- 练习3.6:编写一段程序,使用范围for语句将字符串内的所有字符用x代替
#include <iostream>
using namespace std;
int main()
{
string forChange = "abcdefg hijklmn ,./0-=";
cout << forChange<<endl;
for(auto &c : forChange)
{
c = 'X';
}
cout << forChange<<endl;
return 0;
}
- 练习3.7:就上一题完成的程序而言,如果将循环控制变量的类型设为char将发生什么 ?先估计一下结果 ,然后实际编程进行验证。
如果是声明char而不是引用,那么事实上只改变了一个新定义的char变量的值,而不能改变string的值。
#include <iostream>
using namespace std;
int main()
{
string forChange = "abcdefg hijklmn ,./0-=";
cout << forChange<<endl;
for(auto c : forChange) //注意此处去除了引用
{
c = 'X';
}
cout << forChange<<endl;
return 0;
}
最后输出:
abcdefg hijklmn ,./0-=
abcdefg hijklmn ,./0-=
- 练习3.8:分别用while循环和传统的for循环重写第一题的程序,你觉得哪种形式更好?为什么?
//使用for循环
#include <iostream>
using namespace std;
int main()
{
string forChange = "abcdefg hijklmn ,./0-=";
cout << forChange<<endl;
for(unsigned int i = 0; i < forChange.size(); i++)
{
forChange[i] = 'X';
}
cout << forChange<<endl;
return 0;
}
//使用while循环
#include <iostream>
using namespace std;
int main()
{
string forChange = "abcdefg hijklmn ,./0-=";
cout << forChange<<endl;
unsigned int i = 0;
while(i<forChange.size()){
forChange[i] = 'X';
i++;
}
cout << forChange<<endl;
return 0;
}
使用while循环和for循环之间没有太大区别,与范围for语句的区别在于,使用范围for语句不需要手动维护下标,可以直接进行修改;使用循环的自由度更高。
- 练习3.9:下面的程序有何作用?它合法吗?如果不合法,为什么?
string s;
cout << s[0] << endl;
从语法上来说是合法的,但是从逻辑上来说不合法,因为s仅有一个默认的空值,取s[0]会导致超出范围。
- 练习3.10 :编写一段程序 ,诗篇一个包含标点符号的字符串,将标点符号去除后输出字符串剩余的部分。
#include <iostream>
using namespace std;
int main()
{
string input,output;
getline(cin,input);
for(auto&& c : input)
{
if(ispunct(c)) continue;
output+=c;
}
cout << output<<endl;
return 0;
}
- 练习3.11 :下面的范围for语句合法吗?如果合法,c的类型是什么 ?
const string s = "Keep out!";
for(auto &c :s) { }
合法,c的类型是char &。