在 C++ 中,你可以使用 std::string 类的成员函数 substr 来截取一个字符串的子字符串。substr 函数接受两个参数:起始位置和子字符串的长度。在这种情况下,你需要找到目标子字符串 'arecord' 在原始字符串中的起始位置,然后使用 substr 函数来截取它。

下面是一个示例代码:

#include <iostream>
#include <string>

int main() {
    std::string str = 'this is a test arecord of substrings';
    std::string target = 'arecord';

    // 找到目标子字符串的起始位置
    size_t startPos = str.find(target);

    if (startPos != std::string::npos) {
        // 使用substr函数截取目标子字符串
        std::string result = str.substr(startPos);

        std::cout << '截取的子字符串:' << result << std::endl;
    } else {
        std::cout << '未找到目标子字符串' << std::endl;
    }

    return 0;
}

这段代码首先使用 find 函数找到目标子字符串 'arecord' 在原始字符串中的起始位置。如果找到了目标子字符串,就使用 substr 函数从起始位置开始截取子字符串;否则,输出未找到目标子字符串的消息。

运行上述代码,输出将是:

截取的子字符串:arecord of substrings
C++ 截取字符串:从字符串中提取特定内容 (arecord 例子)

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

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