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开发中的字符串处理提供帮助。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值