C++ 中如何截取字符串

在 C++ 中,可以使用 substr() 函数从字符串中截取一部分。substr() 函数接受两个参数:

  • 起始位置: 要截取的子字符串的起始索引(从 0 开始)。* 截取长度: 要截取的字符数。

例如,要从字符串 'FCFC' 中截取 'FF',可以使用以下代码:c++#include #include

int main() { std::string str = 'FCFC'; std::string result = str.substr(2, 2); // 从索引 2 开始截取 2 个字符 std::cout << result << std::endl; // 输出 'FF' return 0;}

代码解释:

  1. std::string str = 'FCFC'; 声明一个名为 str 的字符串,并初始化为 'FCFC'。2. std::string result = str.substr(2, 2); 使用 substr(2, 2)str 的索引 2 开始截取 2 个字符,并将结果存储在 result 中。3. std::cout << result << std::endl;result 的值(即 'FF')输出到控制台。

总结:

使用 substr() 函数可以方便地从 C++ 字符串中截取指定位置和长度的子字符串。 通过调整起始位置和截取长度,可以灵活地提取所需的字符串片段。

C++ 截取字符串:获取子字符串的方法详解

原文地址: https://www.cveoy.top/t/topic/fvZ1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录