开发者

Split array char

How can i split one array char to two ano开发者_JS百科ther array char? for example :

char array1[9]={10011010}; char array2[5],array3[5];

now i want put 1001 in array2 and 1010 in array3 how can i this request?


Many ways. Two that come to mind are memcpy and std::copy.

#include <cstring>
memcpy(array2, array1, 4);
memcpy(array3, array1+4, 4);

or

#include <algorithm>
std::copy(array1, array1+4, array2);
stdd::copy(array1+4, array1+8, array3);

It seems from your array sizes that you keep one more byte than you need. Perhaps these are character strings, in addition to being simple arrays? If so, please remember to put a null byte at the end of the arrays before you use them:

array2[4] = 0;
array3[4] = 0;


You could use a for loop, memcpy or STL's copy algorithm.


Well, your first array is 9 chars. If you split it into two, one must be 5 and one must be 4 chars. This should do the trick:

char array1[9] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; // not a null-terminated string
int len = sizeof(array1)/sizeof(array1[0]);
int len1 = len / 2;
int len2 = len - len1;
char* array2 = new char[len1];
char* array3 = new char[len2];

memcpy(array2, array1, len1);
memcpy(array3, array1 + len1, len2);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜