简体   繁体   English

如何与string :: copy C ++相反?

[英]How to do the opposite of string::copy C++?

How to copy std::string to specific index in char array in C++ ? 如何在C ++中将std :: string复制到char数组中的特定索引?

example : 例如:

    std::string str = "aaaabbb";
    unsigned char arr[3];
    str.copyToFunction(arr,4,3);

result : 结果:

    arr value should be = "bbb".

Thanks. 谢谢。

Edit: 编辑:

Does it works with std::array ? 它可以与std :: array一起使用吗? or there is another way to do it? 还是有另一种方法?

std::copy(str.begin() + 4, str.begin() + 4 + 3, arr); std :: copy(str.begin()+ 4,str.begin()+ 4 + 3,arr);

std::copy documentation std :: copy文档

Try this: 尝试这个:

std::string str = "aaaabbb";
std::vector<char> myvector (7);
std::copy ( str, str+7, myvector.begin()+4, myvector.end() );

Without bounds checking (which you probably need to do first): 没有边界检查(您可能首先需要做):

std::copy(str.begin() + 4, str.end(), arr);

Note there is no null termination, which you probably want to add: 请注意,没有空终止,您可能要添加:

auto end = std::copy(str.begin() + 4, str.end(), arr);
*end++ = '\0';

Of course arr must now have length 4 at least. 当然, arr现在必须至少具有4的长度。

If you want that the array indeed keep string literal "bbb" then you have to declare the array like 如果您希望数组确实保留字符串文字“ bbb”,那么您必须像这样声明数组

    unsigned char arr[4];

Otherwise if you do not need to append the array with the terminating zero then the array can be declared as you did. 否则,如果不需要在数组末尾附加零,则可以像声明数组一样声明数组。

You can use for example a standard C function declared in header <cstring> . 您可以使用例如在标头<cstring>声明的标准C函数。

#include <cstring>

//...


memcpy( arr, str.c_str() + 4, 3 );

Or you can use standard algorithm std::copy declared in header <algorithm> 或者,您可以使用标头<algorithm>声明的标准算法std::copy

#include <algorithm>

//...

std::copy( str.begin() + 4, str.begin() + 7, arr );

Or you can rewrite the same using standard function std::next declared in header <iterator> 或者,您也可以使用标头<iterator>声明的标准函数std::next重写相同内容

#include <algorithm>
#include <iterator>    
//...

std::copy( std::next( str.begin(), 4 ), std::next( str.begin(), 7 ), arr );

If you need that the array would contain a string then as I said early you have to append zero 如果您需要数组包含一个字符串,那么正如我前面说的,您必须添加零

    unsigned char arr[4];

    // using some method of copying

    arr[3] = '\0;'

Why not just use substr ? 为什么不只使用substr呢? Very good at chopping up strings 非常擅长切弦

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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