欢迎光临
我们一直在努力

C++小白记:string类用法

目录

1.引言

什么是字符串?

C 风格字符串 vs std::string

2. std::string 基础

定义与初始化

字符串输入与输出

3. 字符串操作

3.1字符串拼接与连接

3.2 比较字符串

3.3 查找与替换

3.4 子字符串与切片

4. 字符串的常用成员函数

4.1 长度与容量

4.2 访问字符

4.3 转换大小写

4.4 其他有用的函数

5. 高级用法

5.1 字符串流(stringstream)

5.2 字符串与其他数据类型的转换

结语:


1.引言

什么是字符串?

字符串是由一系列字符组成的序列,用于表示文本信息。它在编程中被广泛应用于用户交互、文件处理、数据解析等场景。

C 风格字符串 vs std::string

在 C++ 中,有两种主要的字符串类型:

C 风格字符串(C-strings):基于字符数组,以空字符 ('\\0') 结尾。

C++ std::string 类:更高级、功能更丰富的字符串类,封装了字符串操作的复杂性。

C 风格字符串示例:

char cstr[] = "Hello, World!";

std::string 示例:

#include <string>

std::string str = "Hello, World!";


2. std::string 基础

定义与初始化

std::string 是 C++ 标准库中的一个类,位于 <string> 头文件中。它封装了字符序列,并提供了丰富的成员函数用于操作字符串。

初始化有很多中方式,如下图:

这个只要了解一下就行

包含头文件:

#include<string>

初始化示例:

#include <iostream>
#include <string>

int main() {
// 默认构造函数
std::string str1;

// 使用字符串字面值初始化
std::string str2 = "Hello";

// 使用拷贝构造函数
std::string str3(str2);

// 使用部分初始化
std::string str4(str2, 0, 3); // "Hel"

// 使用重复字符初始化
std::string str5(5, 'a');

std::cout << "str1: " << str1 << std::endl;
std::cout << "str2: " << str2 << std::endl;
std::cout << "str3: " << str3 << std::endl;
std::cout << "str4: " << str4 << std::endl;
std::cout << "str5: " << str5 << std::endl;

return 0;
}

输出:

字符串输入与输出

输出字符串:

#include <iostream>
#include <string>

int main() {
std::string gre = "Hello, C++ Strings!";
std::cout << gre << std::endl;
return 0;
}

从用户输入字符串:

#include <iostream>
#include <string>

int main() {
std::string input;
std::cout << "请输入一个字符串:";
std::cin >> input; // 读取直到第一个空白字符
std::cout << "您输入的字符串是:" << input << std::endl;
return 0;
}

读取包含空格的整行字符串:

#include <iostream>
#include <string>

int main() {
std::string line;
std::cout << "请输入一行文本:";
std::getline(std::cin, line);
std::cout << "您输入的文本是:" << line << std::endl;
return 0;
}


3. 字符串操作

常用的字符串操作如下,了解就行:

3.1字符串拼接与连接

使用 + 运算符:

#include <iostream>
#include <string>

int main() {
std::string first = "Hello, ";
std::string second = "World!";
std::string combined = first + second;
std::cout << combined << std::endl; // 输出: Hello, World!
return 0;
}

使用 append() 函数:

// 字符串追加
std::string str="hello";
str.append(", world");
std::cout << str << std::endl;

使用 += 运算符:

// +=拼接字符串
str="data";
str+=" stream";
std::cout << str << std::endl;

3.2 比较字符串

关于字符串的比较,其实是逐个位置按照字符比较,计算机中字符存储的方式是ASCII码表,每个字符对应一个ASCII码值,比较字符就是比较ASCII码值的大小:

这是我从网上找的表格资料,其中一些控制字符也是通过ASCII码存储的:

还可以使用==, !=, <, >, <=, >= 运算符:

string a="apple";
std::string b="Apple";
// 字符串字典序比较
if(a < b){
std::cout << "a is less than b" << std::endl;
}else if (a == b){
std::cout << "a is equal to b" << std::endl;
}else{
std::cout << "a is greater than b" << std::endl;
}

输出:

3.3 查找与替换

使用 find() 查找子字符串:

//查找字符串
std::string text = "The quick brown fox jumps over the lazy dog.";
std::string word = "fox";
auto pos = text.find(word); // 查找子串
if(pos == std::string::npos){ // npos代表未找到
std::cout << "未匹配到内容" << std::endl;
std::cout << pos << std::endl;
}else{
std::cout << "匹配位置: " << pos << std::endl;
}

替换子字符串:

//替换字符串
text = "I like cats.";
std::string from = "cats";
std::string to = "dogs";

pos = text.find(from);
if(pos != std::string::npos){
text.replace(pos,from.length(),to); // 替换指定子串
std::cout << "替换后: " << text << std::endl;
}else{
std::cout << "'"<< from << "'未找到"<<std::endl;
}

3.4 子字符串与切片

使用 substr() 获取子字符串:

//提取子串
str = "Hello, World!";
std::string sub = str.substr(7,5); // 截取:起始下标,截取长度
std::cout << "子串: " << sub << std::endl;

std::string new_sub = str.substr(7); // 只传起始下标,截取到末尾
std::cout << "子串: " << new_sub << std::endl;

注意: 如果省略第二个参数,substr() 会返回从起始位置到字符串末尾的所有字符。


4. 字符串的常用成员函数

4.1 长度与容量

获取字符串长度:

#include <iostream>
#include <string>

int main() {
std::string str = "C++ Programming";
std::cout << "字符串长度: " << str.length() << std::endl; // 输出: 14
// 或者使用 size()
std::cout << "字符串大小: " << str.size() << std::endl; // 输出: 14
return 0;
}

获取字符串容量:

每个 std::string 对象都有一个容量(capacity),表示它当前能够持有的最大字符数,而不需要重新分配内存。

#include <iostream>
#include <string>

int main() {
std::string str = "Hello";
std::cout << "初始容量: " << str.capacity() << std::endl;

str += ", World!";
std::cout << "追加后的容量: " << str.capacity() << std::endl;

return 0;
}

输出示例:

初始容量: 15
追加后的容量: 15

注意: 容量可能因实现而异,并不保证它等于长度,容量是一个指数级扩充。

4.2 访问字符

对字符串中的字符操作,有如下方法, 切记需包含头文件:

使用索引访问单个字符:

#include <iostream>
#include <string>

int main() {
std::string str = "ABCDE";

// 正向索引
for (int i = 0; i < str.length(); i++) {
std::cout << "字符 " << i << ": " << str[i] << std::endl;
}

//反向遍历
for(int i = str.length() – 1; i >= 0 ; i –){
std::cout << "下标为 " << i << "的字符为" << str[i] << std::endl;
}

return 0;
}

使用 at() 函数(包含边界检查):

//try-catch捕获异常
#include <iostream>
#include <string>

int main() {
std::string str = "ABCDE";
try {
char c = str.at(10); // 超出范围,会抛出异常
} catch (const std::out_of_range& e) {
std::cout << "异常捕获: " << e.what() << std::endl;
}
return 0;
}

4.3 转换大小写

C++ 标准库中的 std::toupper 和 std::tolower 可以用于转换字符的大小写。结合 std::transform,可以实现整个字符串的大小写转换。

转换为大写:

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

int main() {
std::string str = "Hello, World!";
// 全部转大写
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c){ return std::toupper(c);}); // lambda表达式,接收一个字符c,对c进行转大写操作
std::cout << str << std::endl;

// 以小写为例,上面的逻辑相当于,迭代器遍历全部转小写
for(auto iter = str.begin(); iter != str.end(); iter++){
*iter = std::tolower(*iter);
}
std::cout << str << std::endl;
return 0;
}

4.4 其他有用的函数

empty():检查字符串是否为空:

std::string str;
if (str.empty()) {
std::cout << "字符串为空。" << std::endl;
}

clear():清空字符串内容:

std::string str = "Clear me!";
str.clear();
std::cout << "str: " << str << std::endl; // 输出为空

erase():删除字符串的部分内容:

std::string str = "Hello, World!";
str.erase(5, 7); // 从位置5开始,删除7个字符
std::cout << str << std::endl; // 输出: Hello!

insert():在指定位置插入字符串或字符:

std::string str = "Hello World";
str.insert(5, ",");
std::cout << str << std::endl; // 输出: Hello, World

replace():替换字符串的部分内容(前面已示例)。

find_first_of(), find_last_of():查找字符集合中的任何一个字符。

std::string str = "apple, banana, cherry";
size_t pos = str.find_first_of(", ");
std::cout << "第一个逗号或空格的位置: " << pos << std::endl; // 输出: 5


5. 高级用法

5.1 字符串流(stringstream)

std::stringstream 是 C++ 标准库中第 <sstream> 头文件提供的一个类,用于在内存中进行字符串的读写操作,类似于文件流。

基本用法示例:

#include <iostream>
#include <sstream>
#include <string>

int main() {
std::stringstream ss;
ss << "Value: " << 42 << ", " << 3.14;

std::string result = ss.str();
std::cout << result << std::endl; // 输出: Value: 42, 3.14

return 0;
}

从字符串流中读取数据:

// 字符串分割提取数字、字符串
std::string data = "123 45.67 Hello";
std::stringstream ss1(data); //将字符串存入流中
int a1;
double b1;
std::string c;
ss1 >> a1 >> b1 >> c;
std::cout << "a1: " << a1 << ", b1: " << b1 << ", c: " << c << std::endl;
// 输出: a: 123, b: 45.67, c: Hello

5.2 字符串与其他数据类型的转换

将其他类型转换为 std::string:

使用 std::to_string():

// 数字转字符串 to_string
int num = 100;
double pi = 3.14159;
str1 = std::to_string(num);
str2 = std::to_string(pi);
std::cout << "str1: " << str1 << ", str2: " << str2 << std::endl;
// 输出: str1: 100, str2: 3.141590

将 std::string 转换为其他类型:

使用字符串流:

#include <iostream>
#include <sstream>
#include <string>

int main() {
std::string numStr = "256";
std::string piStr = "3.14";

int num;
double pi;

std::stringstream ss1(numStr);
ss1 >> num;

std::stringstream ss2(piStr);
ss2 >> pi;

std::cout << "num: " << num << ", pi: " << pi << std::endl;
// 输出: num: 256, pi: 3.14
return 0;
}

使用 std::stoi(), std::stod() 等函数(C++11 及以上):

#include <iostream>
#include <string>

int main() {
std::string numStr = "256";
std::string piStr = "3.14";

int num = std::stoi(numStr);
double pi = std::stod(piStr);

std::cout << "num: " << num << ", pi: " << pi << std::endl;
// 输出: num: 256, pi: 3.14
return 0;
}

这个用法就会简单很多。


结语:

今日任务是学习string类的一些用法,Fighting!

    赞(0)
    未经允许不得转载:171主机测评 » C++小白记:string类用法
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址