• 使用string类要加头文件#include<string>

  • 下面的例子介绍了几种定义 string 变量(对象)的方法:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string s1;
    string s2 = "c plus plus";
    string s3 = s2;
    string s4 (5, 's');
    return 0;
}

变量 s1 只是定义但没有初始化,编译器会将默认值赋给 s1,默认值是空字符串。

变量 s2 在定义的同时被初始化为"c plus plus"。与C风格的字符串不同,string 的结尾没有结束标志'\0'

变量 s3 在定义的时候直接用 s2 进行初始化,因此 s3 的内容也是"c plus plus"

变量 s4 被初始化为由 5 个's'字符组成的字符串,也就是"sssss"。

  • 与C风格的字符串不同,当我们需要知道字符串长度时,可以调用 string 类提供的 length() 函数。如下所示:
string s = "Hello World!";
int len = s.length();
cout<<len<<endl;

由于 string 的末尾没有'\0'字符,所以 length() 返回的是字符串的真实长度,而不是长度 +1

  • 转换为C风格的字符串
    虽然 C++ 提供了 string 类来替代C语言中的字符串,但是在实际编程中,有时候必须要使用C风格的字符串(例如打开文件时的路径),为此,string 类为我们提供了一个转换函数 c_str(),该函数能够将 string 字符串转换为C风格的字符串,并返回该字符串的 const 指针(const char*)。
  • string 字符串的增删改查

- 一. 插入字符串

insert() 函数可以在 string 字符串中指定的位置插入另一个字符串,它的一种原型为:

string& insert (size_t pos, const string& str);

pos 表示要插入的位置,也就是下标;str 表示要插入的字符串,它可以是 string 字符串,也可以是C风格的字符串。

-二. 删除字符串

erase() 函数可以删除 string 中的一个子字符串。它的一种原型为:

string& erase (size_t pos = 0, size_t len = npos);

pos 表示要删除的子字符串的起始下标,len 表示要删除子字符串的长度。如果不指明 len 的话,那么直接删除从 pos 到字符串结束处的所有字符(此时 len = str.length - pos)。

- 三. 提取子字符串

substr() 函数用于从 string 字符串中提取子字符串,它的原型为:

string substr (size_t pos = 0, size_t len = npos) const;

pos 为要提取的子字符串的起始下标,len 为要提取的子字符串的长度。

-四. 字符串查找

ind() 函数用于在 string 字符串中查找子字符串出现的位置,它其中的两种原型为:

size_t find (const string& str, size_t pos = 0) const;
size_t find (const char* s, size_t pos = 0) const;

第一个参数为待查找的子字符串,它可以是 string 字符串,也可以是C风格的字符串。第二个参数为开始查找的位置(下标);如果不指明,则从第0个字符开始查找。