简体   繁体   中英

Copy a part of an std::string in a char* pointer

Let's suppose I've this code snippet in C++

char* str;
std::string data = "This is a string.";

I need to copy the string data (except the first and the last characters) in str . My solution that seems to work is creating a substring and then performing the std::copy operation like this

std::string substring = data.substr(1, size - 2);
str = new char[size - 1];
std::copy(substring.begin(), substring.end(), str);
str[size - 2] = '\0';

But maybe this is a bit overkilling because I create a new string. Is there a simpler way to achieve this goal? Maybe working with offets in the std:copy calls?

Thanks

There is:

int length = data.length() - 1;
memcpy(str, data.c_str() + 1, length);
str[length] = 0; 

This will copy the string in data, starting at position [1] (instead of [0] ) and keep copying until length() - 1 bytes have been copied. (-1 because you want to omit the first character).

The final character then gets overwritten with the terminating \0 , finalizing the string and disposing of the final character.

Of course this approach will cause problems if the string does not have at least 1 character, so you should check for that beforehand.

If you must create the new string as a dynamic char array via new you can use the code below.

It checks whether data is long enough, and if so allocates memory for str and uses std::copy similarly to your code, but with adapted iterators.
There is no need to allocate another std::string for the sub-string.

#include <string>
#include <iostream>

int main() 
{
    std::string data = "This is a string.";
    auto len = data.length();
    char* str = nullptr;
    if (len > 2)
    {
        auto new_len = len - 2;
        str = new char[new_len+1];  // add 1 for zero termination
        std::copy(data.begin() + 1, data.end() - 1, str);  // copy from 2nd char till one before the last
        str[new_len] = '\0';  // add zero termination
        std::cout << str << std::endl;
    }
    // ...
    delete[] str;   // must be released eventually
}

Output:

his is a string

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