简体   繁体   中英

How to copy std::string to std::string with parameters?

I can't solve the problem with the copying strings with parameters. I have found the way to do it with char * pointers, but they are actually wasting extra resources:

using namespace std;
...
string word, halfWord_0S, halfWord_1S;
char halfWord_0[100], halfWord_1[100];
...
if ((i % 2) == 0)
    {
        word.copy(halfWord_0, (i / 2), 0);
        word.copy(halfWord_1, (i / 2), ((i / 2)));
    }   else    {
        word.copy(halfWord_0, ((i / 2) + 1), 0);
        word.copy(halfWord_1, ((i / 2) + 1), (i / 2));
    }
    halfWord_0S = halfWord_0;
    halfWord_1S = halfWord_1;
...

I want to work only with std::string without char * . Is this possible in this case?

Try to use this snippet:

std::string base = "some text";
std::string half = base.substr(0, base.length()/2);
std::string secondHalf = base.substr(base.length()/2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM