c++之标准库类型string

来源:互联网 发布:mysql 获取上一年月份 编辑:程序博客网 时间:2024/06/06 10:44

标准库类型string 表示可变长的字符序列,使用string类型必须首先包含string头文件。

#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]);
原创粉丝点击