【C++】C++中substr的用法

本文详细介绍了C++中字符串的substr方法使用技巧。substr方法有两种主要用途:一是通过指定起始位置截取到字符串末尾;二是通过指定起始位置及长度来精确截取所需子串。这对于字符串处理非常实用。

substr有2种用法:
假设:string s = "0123456789";

string sub1 = s.substr(5); //只有一个数字5表示从下标为5开始一直到结尾:sub1 = "56789"

string sub2 = s.substr(5, 3); //从下标为5开始截取长度为3位:sub2 = "567"

C++中,`substr` 是 `std::string` 类的成员函数,用于从一个字符串中提取子字符串。其函数原型为 `string substr(size_t pos = 0, size_t len = npos) const;`,其中 `pos` 是开始提取的位置,默认值为 0;`len` 是要提取的子字符串的长度,默认值为 `npos`,表示直到字符串的末尾 [^3]。 以下是一些常见的使用场景和示例: #### 提取从指定位置开始到字符串末尾的子字符串 ```cpp #include <iostream> #include <string> int main() { std::string s = "0123456789"; std::string sub1 = s.substr(5); // 从下标为5开始一直到结尾 std::cout << "从位置5开始到结尾: " << sub1 << std::endl; // 输出: 56789 return 0; } ``` #### 提取从指定位置开始的指定长度的子字符串 ```cpp #include <iostream> #include <string> int main() { std::string s = "0123456789"; std::string sub2 = s.substr(5, 3); // 从下标为5开始截取长度为3位 std::cout << "从位置5开始长度为3: " << sub2 << std::endl; // 输出: 567 return 0; } ``` #### 使用默认参数 ```cpp #include <iostream> #include <string> int main() { std::string s = "HelloWorld"; std::string sub = s.substr(); // 默认从位置0开始,截取整个字符串 std::cout << "默认构造参数: " << sub << std::endl; // 输出: HelloWorld return 0; } ``` #### 与 `find` 函数配合使用,提取特定子字符串 ```cpp #include <iostream> #include <string> int main() { std::string s = "Hello,World! How are you?"; size_t pos = s.find(","); // 找到逗号的位置 if (pos != std::string::npos) { std::string sub = s.substr(pos + 1); // 从逗号后面开始提取子字符串 std::cout << "从逗号后开始的子字符串: " << sub << std::endl; } return 0; } ```
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值