使用命令 std::string::substr 将字符串拆分为C++

Split the string in C++ using command std::string::substr

本文关键字:字符串 拆分 C++ string 命令 std substr      更新时间:2023-10-16

我能够得到字符串的前半部分:

 insert1 = tCreatureOne.substr(0, (tCreatureOne.length) / 2

我不知道如何获得字符串的后半部分

insert2 = tCreatureOne.substr((tCreatureOne.length) / 2), ?????)

这是我的代码。

// Insert creature two in to the
//middle of creature one.Science!
// Hamster and Emu make a HamEmuster
std::string PerformScience(std::string tCreatureOne, std::string tCreatureTwo)
{
    std::string insert1;
    std::string insert2;
    std::string insert3;

        // first half : 0 to middle
        insert1 = tCreatureOne.substr(0, (tCreatureOne.length) / 2); 
    // last half: from middle to the end
        insert2 = tCreatureOne.substr((tCreatureOne.length) / 2), tCreatureOne.length); 
        insert3 = insert1 + tCreatureTwo + insert2;
    return insert3;

可能最重要的开发人员技能是知道如何进行在线研究。谷歌搜索"c ++ substr"显示这是最重要的结果:http://www.cplusplus.com/reference/string/string/substr/

在描述参数的部分中,len描述如下:

要包含在子字符串中的字符数(如果字符串较短,则使用尽可能多的字符)。
字符串::npos 的值指示字符串末尾之前的所有字符。

所以你可以写:

insert2 = tCreatureOne.substr(tCreatureOne.length() / 2), std::string::npos);

但是,请注意,substr声明如下:

string substr (size_t pos = 0, size_t len = npos) const;

意思是len非常方便地默认为 npos .
因此,您可以更简单地编写:

insert2 = tCreatureOne.substr(tCreatureOne.length() / 2));

但是,即使substr没有指定"字符串的其余部分"的方便方法,您仍然可以轻松地按如下方式计算它:

int totalLength = tCreatureOne.length();
int firstLength = totalLength / 2;
int remainderLength = totalLength - firstLength;
//So...
insert2 = tCreatureOne.substr(tCreatureOne.length() / 2), remainderLength);

πάντα ῥεῖ 在他们的注释中是正确的 - 要检索字符串的后半部分,您无需指定第二个参数(字符串的末尾):

insert2 = tCreatureOne.substr(tCreatureOne.length() / 2);

上面的行将正常工作。另外,由于您使用的是 std::string ,请记住将括号添加到length()调用中。