问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

C++中的`string`类型:全面解析与高效操作

创作时间:
作者:
@小白创作中心

C++中的`string`类型:全面解析与高效操作

引用
1
来源
1.
https://cloud.tencent.com/developer/article/2493639

C++中的string类型是对字符数组的高级封装,它提供了大量内置函数,使得字符串的处理变得更为简便和高效。本文将通过详细讲解string类型的概念、常见操作及相关函数,帮助你快速掌握这一强大工具。

1. string类型的概念

在C++中,string类型属于标准库中的std命名空间。它实际上是一个类,封装了字符串操作的多个方法,使得我们无需手动管理字符数组的内存,避免了C语言中的常见问题(如字符串长度限制、手动添加结束符\0)。通过string类型,我们可以更方便、更安全地操作文本数据。

创建string对象:

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1;         // 创建空字符串
    string s2 = "abc"; // 创建并初始化字符串
    cout << "s1: " << s1 << endl; // 输出空字符串
    cout << "s2: " << s2 << endl; // 输出 abc
    return 0;
}
  • string s1; 创建一个空字符串。
  • string s2 = "abc"; 通过字面量初始化字符串。

2. 常见的string操作

2.1 字符串的输入与输出

使用cin输入字符串:

string s;
cin >> s; // 读取不带空格的字符串
cout << s << endl; // 输出输入的字符串
  • cin读取时遇到空格会停止。

使用getline输入带空格的字符串:

getline是C++标准库中的一个函数,用于从输入流中读取一行文本,并将其存储为字符串。与cin不同,getline可以读取包括空格在内的整行字符串。

格式:

istream& getline(istream& is, string& str);
  • 这种形式的getline以换行符(\n)作为字符串的结束标志。
  • 它从输入流中读取文本,直到遇到换行符为止,然后将读取到的文本(不包括换行符)存储到指定的string类型变量str中。

示例代码:

#include<iostream>
#include<string>
using namespace std;
int main() {
    string name;
    getline(cin, name);  // 从键盘读取一行文本
    cout << name << endl;  // 输出读取的字符串
    return 0;
}

运行时,输入的字符串(包括空格)将被读取并存储在name变量中,然后输出。

getline的第二种形式:

格式:

istream& getline(istream& is, string& str, char delim);
  • 这种形式允许用户自定义结束标志(delim),即指定一个字符作为字符串的结束标志。
  • 它会从输入流中读取文本,直到遇到指定的字符为止,然后将读取到的文本(不包括该字符)存储到指定的string类型变量str中。

示例代码:

#include<iostream>
#include<string>
using namespace std;
int main() {
    string name;
    getline(cin, name, 'q');  // 从键盘读取一行文本,直到遇到字符 'q'
    cout << name << endl;  // 输出读取的字符串
    return 0;
}

在这个例子中,输入的文本会读取直到遇到字符q为止。q字符不会被包含在最终的字符串中。

小提示:在使用C++中的string字符串时,如果字符串中需要包含空格,getline函数是必须的。它在字符串输入时非常常见,尤其是在竞赛中处理字符串输入时,通常会使用string类型的字符串。

2.2 获取字符串长度

使用size()获取字符串的长度:

string s = "hello";
cout << "Length of string: " << s.size() << endl; // 输出 5
  • size()返回字符串的字符数。

2.3 迭代器操作

C++中的string提供了迭代器,可以用于遍历字符串中的元素。(不过访问迭代器指向的值,需要解引⽤(*)。)

正序遍历:

string s = "abcdef";
for (auto it = s.begin(); it != s.end(); ++it) {
    cout << *it << " "; // 输出字符
}

逆序遍历:

string s = "abcdef";
for (auto it = s.end() - 1; it >= s.begin(); --it) {
    cout << *it << " "; // 输出字符
}

✅ 小提⽰:

  • 迭代器是可以进⾏⼤⼩⽐较,也可以进⾏+或者-
    整数运算的。⽐如:it++,就是让迭代器前进⼀步,it--就是让迭代器退后⼀步。
  • 同⼀个容器的两个迭代器也可以相减,相减结果的绝对值,是两个迭代器中间元素的个数。

2.4 添加字符:push_back()

push_back()用于在字符串末尾添加一个字符:

string s = "hello";
s.push_back('w');
cout << s << endl;  // 输出 hellow

2.5 字符串拼接:+=+运算符

C++中的string支持+=+运算符,用于字符串拼接:

string s1 = "hello";
s1 += " world";  // 拼接字符串
cout << s1 << endl;  // 输出 hello world
string s2 = "hello";
cout << s2 + " world" << endl;  // 输出 hello world

2.6 删除字符:pop_back()

pop_back()用于删除字符串末尾的一个字符:

string s = "hello";
s.pop_back();  // 删除 'o'
cout << s << endl;  // 输出 hell
  • 注意:当字符串为空时,再调用pop_back()会导致程序崩溃。

2.7 插入字符:insert()

insert()方法允许你在字符串的指定位置插入字符或子串。

插入字符串:

string s = "abcdefghi";
s.insert(3, "xxx");  // 在位置3插入字符串 "xxx"
cout << s << endl;  // 输出 abcdxxxefghi

插入多个相同字符:

s.insert(3, 3, 'x');  // 在位置3插入3个字符 'x'
cout << s << endl;  // 输出 abcdxxxefghi

2.8 查找字符串:find()

find()方法用于查找字符串中的子串或字符,并返回第一次出现的位置。若未找到,则返回string::npos

查找子串:

string s = "hello world hello everyone";
size_t pos = s.find("llo");
cout << "Found 'llo' at position: " << pos << endl;  //输出2

查找字符:

string s = "hello world";
size_t pos = s.find('o');
cout << "Found 'o' at position: " << pos << endl;  // 输出 4

查找失败:

string s = "hello world";
size_t pos = s.find("xyz");
if (pos != string::npos) {
    cout << "Found at position: " << pos;
} else {
    cout << "Not found" << endl;
}

2.9 截取子串:substr()

substr()用于从字符串中截取子串,支持指定位置和长度。

截取指定位置后的子串:

string s = "hello world";
string sub = s.substr(7);
cout << sub << endl;  // 输出 world

截取指定位置和长度的子串:

string s = "hello world";
string sub = s.substr(7, 6);
cout << sub << endl;  // 输出 orld h

2.10 字符串关系运算符

C++提供了一些常用的字符串比较运算符,如==!=<>等,比较是基于字典顺序进行的。

字符串相等比较:

string s1 = "hello";
string s2 = "hello";
if (s1 == s2) {
    cout << "Equal" << endl;  // 输出 Equal
}

字符串大小比较:

string s1 = "apple";
string s2 = "banana";
if (s1 < s2) {
    cout << "apple is less than banana" << endl;
}

2.11 字符串转数字:stoi()stol()stod()

这些函数将字符串转换为整数、长整型或浮点型:

string s = "123";
int num = stoi(s);
cout << num << endl;  // 输出 123
string s2 = "3.14";
double pi = stod(s2);
cout << pi << endl;  // 输出 3.14

2.12 将数字转换为字符串:to_string()

to_string()将数字转换为字符串:

int num = 123;
string str = to_string(num);
cout << str << endl;  // 输出 123

3. 总结

C++的string类型为处理字符串提供了强大而高效的工具。通过使用诸如insert()find()substr()等函数,我们可以轻松地在字符串中进行插入、查找、截取等操作,避免了传统字符数组的复杂性。此外,运算符重载和转换函数使得字符串与其他数据类型之间的转换变得简便。掌握这些技巧,你将能够在实际开发中更高效地处理字符串相关问题。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号