您的位置:首页 > 编程语言 > C语言/C++

c++之标准库类型string

2017-07-25 09:11 260 查看
标准库类型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]);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string