[英]Copy a part of an std::string in a char* pointer
Let's suppose I've this code snippet in C++假设我在 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
.我需要复制str
中的字符串data
(第一个和最后一个字符除外)。 My solution that seems to work is creating a substring and then performing the std::copy
operation like this我似乎可行的解决方案是创建一个 substring 然后像这样执行std::copy
操作
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?也许在std:copy
调用中使用offets ?
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.这将复制数据中的字符串,从 position [1]
(而不是[0]
)开始并继续复制直到length() - 1
个字节被复制。 (-1 because you want to omit the first character). (-1 因为你想省略第一个字符)。
The final character then gets overwritten with the terminating \0
, finalizing the string and disposing of the final character.最后一个字符然后被终止\0
覆盖,最终确定字符串并处理最后一个字符。
Of course this approach will cause problems if the string does not have at least 1 character, so you should check for that beforehand.当然,如果字符串没有至少 1 个字符,这种方法会导致问题,因此您应该事先检查。
If you must create the new string as a dynamic char
array via new
you can use the code below.如果您必须通过new
将新字符串创建为动态char
数组,您可以使用下面的代码。
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.它检查data
是否足够长,如果是,则为str
分配 memory 并使用类似于您的代码的std::copy
,但使用经过调整的迭代器。
There is no need to allocate another std::string
for the sub-string.无需为子字符串分配另一个std::string
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: Output:
his is a string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.