将 std::string 和字符数组分成两半(有效地)

Qui*_*tic 3 c c++ string

我们如何将 astd::string和一个以空字符结尾的字符数组分成两半,使它们的长度相同?

请为此提出一种有效的方法。您可能会假设原始字符串/数组的长度始终是偶数。

有效地我的意思是在这两种情况下都使用更少的字节数,因为使用循环和缓冲区的东西不是我想要的。

Naw*_*waz 6

    std::string s = "string_split_example";
    std::string half = s.substr(0, s.length()/2);
    std::string otherHalf = s.substr(s.length()/2);

    cout << s.length() << " : " << s << endl;
    cout << half.length()  << " : " << half << endl;
    cout << otherHalf .length()  << " : " << otherHalf  << endl;
Run Code Online (Sandbox Code Playgroud)

输出:

20 : string_split_example
10 : string_spl
10 : it_example
Run Code Online (Sandbox Code Playgroud)

在线演示:http : //www.ideone.com/fmYrO