【Cpp 语言基础】 string 类型进阶使用

发布时间 2023-12-27 21:40:00作者: FBshark

大纲:

1. 特殊的初始化方式

2. 获取子串

3. 与<algorith>中对应的成员函数

 

”串“类型类似于数组类型(C语言的字符串就是字符数组)。但是有一点不同之处,就是串经常作为一个整体才有实际的”意义“,而数组每个单元都有其”意义“。

因此,“串”的操作中,很大部分是“串”的整体、局部为单元,而非以个体为单元。

1. 特殊的初始化方式

除了采用以下传统的方式初始化,sting类型还有其他方式初始化:

string str1;
string str1(str2);
string str1(cstr);//cstr表示 C风格的字符串
string str1("Hello world");

其他的初始化方式大多与子串有关。

string str1(cstr, n);//n为C风格字符数组的下标
string str1(cstr, n, cnt);
string str1(str2, n);
string str1(str2, n, cnt);

string str1(str2, iter);//iter为string类型的迭代器,类似于vector<char>类型的迭代器
string str1(str2, iter1, iter2);

2. 获取子串 str.substr()方法

可以利用 string 类的substr()方法来求取子串:

string str1 = str2.substr(n1, n2);
string str1 = str2.substr(n1);

3. 与<algorithm>中对应的成员函数

 algorithm标准库中,有针对 vector类型的泛型算法,比如 find(), sort(), stable_sort() 等等函数,其基于迭代器。

但 string 类型的迭代器不常用,当用到算法的时候,string类型有其自己的一套“私人武器“。

比如 str.find() ,应用如下所示:

std::string myString = "Hello, world!";

size_t found = myString.find("Cat");
if (found == std::string::npos) {
    std::cout << "Substring not found." << std::endl;
} else {
    std::cout << "Substring found at position " << found << std::endl;
}

在上面的例子中,我们使用find()函数查找子字符串"Cat"在myString中的位置。如果子字符串不存在,则find()函数返回std::string::npos,我们可以使用它来判断子字符串是否存在于原字符串中。 

里面的 std::string::npos 是什么意思?

#include <iostream>
#include <string>

using namespace std;
int main()
{
    //不能单独使用 npos,哪怕声明了 using namespace std;
    //cout << "npos == " << npos <<endl; //编译出错:error: 'npos' was not declared in this scope
    cout << "npos == " << string::npos <<endl; //输出为:npos == 4294967295
    return 0;
}

std::string::npos是C++标准库中string类的静态成员变量,它表示一个无效的或者不存在的字符串位置或索引。这个值在string类中通常用于查找或搜索某个子字符串或字符的位置,当find()rfind()等函数无法找到所需的子字符串或字符时,它们会返回std::string::npos作为标记表示查找失败。

std::string::npos的值通常是一个非常大的整数,因为它需要能够区别于任何字符串中可能出现的有效位置或索引。具体的值可能因实现而异,但通常被定义为-14294967295std::string::size_type类型的最大值,通常为无符号整数类型)。

在使用find()rfind()等函数时,我们通常使用std::string::npos作为查找失败的返回值的标记。