c++之标准库类型string
2017-07-25 09:11
260 查看
标准库类型string 表示可变长的字符序列,使用string类型必须首先包含string头文件。
读取未知数量的对象
使用getline读取一整行
处理每个字符?使用基于范围的for循环
使用for语句改变字符串中的字符
只处理一部分字符?
#include <string> using namesapce std;
读取未知数量的对象
int main() { string word; while(cin << word)//使用一个istream对象作为条件,其效果是检查流的状态。当遇到文件结束符或无效输入时,条件变为假。 cout << word << endl; return 0; }
使用getline读取一整行
int main() { string line; //函数从给定的的输入流中读入内容,直到遇到换行符为止 while (getline(cin, line)) //每次读入一整行,遇到空行跳过 if(!line.empty()) //只输出长度超过80个字符的行 //if(line.size() > 80) cout << line << endl; return 0; }
处理每个字符?使用基于范围的for循环
for(定义一个变量 : 一个string对象)//该变量被用于访问序列中的基础元素 语句;
//使用for语句和ispunct()来统计string对象中标点符号的个数 string s("Hllo World!!!"); //关键字decltype声明计数变量punct_num的类型为s.size()返回的类型(也就是string::size_type) decltype(s.size()) punct_num = 0; for(auto c : s) if (ispunct(c)) ++punct_num; cout << punct_num << endl;
使用for语句改变字符串中的字符
string s("Hello World!!!") for(auto &c : s) //c是引用将改变s中字符的值 c = toupper(c); cout << s << endl;
只处理一部分字符?
//将字符串首字母改成大写形式 string s("some string"); if (!s.empty()) s[0] = toupper(s[0])
//将第一个词改成大写形式 for (decltype(s.size()) index = 0; index !=s.size() && !isspace(s[index]);++index) //将当前字符改成大写 s[index] = toupper(s[index]);
相关文章推荐
- C++基础<03>—标准库string类型
- c++(19)标准库类型string( 一 )
- C++基础编程----2.2标准库类型string
- 关注C++细节——标准库string类型
- C++ ->Chapter3 标准库类型之读入未知数目的string 对象
- C++ ->Chapter3 标准库类型之string 类型
- C++学习笔记(二)(标准库string类型)
- C++ 标准库 string类型(三)
- C++之标准库类型string(g++)
- c++ 标准库string类型
- C++学习(一)——标准库类型之string全解析
- C++中的标准库类型——string
- C风格字符串和C++的标准库类型string的比较
- c++ 标准库string类型
- C/C++学习笔记33:C++中标准库string类型
- C++基础的不能再基础的学习笔记——标准库类型string
- C++ primer: C++中string标准库类型
- C++ 标准库 string类型(二)
- C++ 标准库 string类型(一)
- C++ 输入字符串和string 类型总结