Qt中QString和std::string的截取函数详解

摘要

摘要:本文将介绍在Qt中使用QString和std::string进行截取的相关函数。我们将详细说明各种常用的截取函数及其使用方法,帮助您在字符串处理中更加灵活和高效。

正文:

QString截取函数

(1)left(n):截取字符串的前n个字符。

QString str = "Hello, World!";
QString result = str.left(5);  // 结果为"Hello"

(2)right(n):截取字符串的后n个字符。

QString str = "Hello, World!";
QString result = str.right(6);  // 结果为"World!"

(3)mid(pos, n):从pos位置开始截取字符串的n个字符。

QString str = "Hello, World!";
QString result = str.mid(7, 5);  // 结果为 "World"

(4)chopped(n):去掉字符串末尾的n个字符。

QString str = "Hello, World!";
QString result = str.chopped(7);  // 结果为 "Hello"

(5)section(sep, start, end):以sep为分隔符,从start位置开始截取到end位置的子字符串。


```cpp
QString str = "apple,orange,banana";
QString result = str.section(',', 1, 1);  // 结果为"orange"

std::string截取函数

(1)substr(pos, n):从pos位置开始截取字符串的n个字符。

std::string str = "Hello, World!";
std::string result = str.substr(7, 5);  // 结果为 "World"

(2)erase(pos, n):从pos位置开始删除字符串的n个字符。

std::string str = "Hello, World!";
str.erase(0, 7);  // 结果为"World!"

(3)replace(pos, n, new_str):从pos位置开始替换字符串的n个字符为new_str。

std::string str = "Hello, World!";
str.replace(0, 5, "Hi");  // 结果为 "Hi, World!"

(4)find(sub_str):查找子字符串sub_str在字符串中的第一个位置。

std::string str = "Hello, World!";
size_t pos = str.find("World");  // 结果为 7

(5)rfind(sub_str):查找子字符串sub_str在字符串中的最后一个位置。

std::string str = "Hello, World!";
size_t pos = str.rfind("o");  // 结果为 7

总结:

本文介绍了在Qt中使用QString和std::string进行截取的相关函数。您可以利用这些函数来轻松截取字符串的子串,使字符串处理更加灵活和高效。希望本文的内容能为您在Qt开发中的字符串处理提供帮助。

猜你喜欢

转载自blog.csdn.net/qq_46017342/article/details/132546602