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

Time:09-02

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

CodePudding user response:

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.

CodePudding user response:

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(void) 
{
    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);
        str[new_len] = '\0';    // add zero termination
        std::cout << str << std::endl;
    }
    // ...
    if (str) delete[] str;  // must be released eventually
}

Output:

his is a string
  • Related