[C++学习]标准库类型string总结

定义与初始化

使用string类型必须包含string的头文件,并且定义在命名空间std中,需要以下代码:

#include <string>
using std::string;

常见初始化string对象的方法

string str1; // str1为空字符串
string str2(str1); //str2为str1的副本
string str3 = str1; // 等价于str3(str1)
string str4("helloworld!"); // str4的字面值为"helloworld"的副本
string str5 = "helloworld!"; // 等价于str5("helloworld!")
string str6(n, 'a'); // 把str6初始化为n个连续字符a组成的字符串

string对象上的操作

1. 读写string对象

string str;
cin >> str;
cout << str << endl;

执行以上代码时,string对象会忽略开头空白(空格符、换行符、制表符等)并且从真正的第一个字符开始,直到遇见下一个空白。例如输入"hello world!"时输出只有"hello"。

读取未知数量的string对象:

string str;
while (cin >> str)
{
    cout << str << endl;
}

结果:

linzijie@DESKTOP-3HKDU47:~/code$ ./string
hello world!
hello
world!

使用getline读取一整行:

string line;
while (getline(cin, line))
{
    cout << line << endl;
}

结果:

linzijie@DESKTOP-3HKDU47:~/code$ ./string
hello world!
hello world!
this is a cpp program!
this is a cpp program!

2. empty与size操作

string line;
while (getline(cin, line))
{
    if (!line.empty())
    {
        cout << "size: " << line.size() << endl;
        cout << line << endl;
    }
}

结果:

linzijie@DESKTOP-3HKDU47:~/code$ ./string

hello world!
size: 12
hello world!

size函数的返回值类型为string::size_type,尽管不清楚其细节,但是它一定为一个无符号类型值,并且能够存放下任何string对象的大小。

3. 比较string对象

相等性运算符 "==" 和 "!=" 分别检验两个string对象的相等和不相等。

关系运算符 "<"、"<="、">"、">=" 检验一个stirng对象小于、小于等于、大于、大于等于另外一个string对象,这些运算符依照以下字典(大小写敏感)顺序:

  • 如果两个string对象长度不同,并且较短string对象的每个字符都与较长string对象对应位置上的字符相同,则较短string对象小于较长string对象。
  • 如果两个string对象在某些对应位置上不一致,则string对象比较的结果其实是string对象中第一对相异字符比较的结果。

4. 字符串相加

string s1 = "hello ";
string s2 = "world!\n";
string s3 = s1 + s2; // s3字面值为"hello world\n"

string s4 = "hello";
string s5 = "world";
string s6 = s4 + " " + s5 + "!\n"; // s6字面值为"hello world\n"

当字面值与string对象相加时,必须保证每个加法运算符的两侧至少有一个时string对象。下面是一些错误写法

string s1 = "hello " + "world!\n"; // 错误写法
string s2 = "world";
string s3 = ("hello" + ",") + s2; // 错误写法

提示:C++中字符串字面值并不是标准库类型string的对象,字符串字面值与string是不同的类型!

5. 处理string对象中的字符

在cctype头文件中定义了一些字符判断与操作, 点击查看

基于for循环的字符处理,统计string对象中小写字母数量:
string str("hello world!");
int lowercase_count = 0;
for (auto c : str)
{
    if (islower(c))
    {
        lowercase_count = lowercase_count + 1;
    }
}
cout << "lowercase count = " << lowercase_count << endl;
部分字符处理

访问string对象中单个字符的方法有两种: 下标和迭代器。

迭代器方法有单独的方法总结,点击查看

下标运算符([ ])接受string::size_type类型参数,这个参数表示要访问的字符位置,返回该位置上字符的引用。下标从0开始,到s.size()-1结束。

使用超过范围的下标将引发不可预知的后果,使用下标访问空string也会引发不可预知的后果。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s("hello world!");
    // C++11新标准引入了decltype类型说明符,它的作用是选择并返回操作数的数据类型
    for(decltype(s.size()) index = 0;
        index != s.size() && !isspace(s[index]); ++index)
            s[index] = toupper(s[index]);
    cout << s << endl;
    return 0;
}
posted @ 2019-09-18 16:25  Dumbledore  阅读(158)  评论(0编辑  收藏  举报