Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting char array into chunks quickly c++

Tags:

c++

arrays

Is there a faster/ more efficient way to split a char array into chunks (say 21 chars/ array) other than looping over the whole array?

This is my attempt right now

const char* arr = line.c_str();
char smallArr[(int)ceil((double)strlen(arr)/(double)21)][21];
int arrSisze[(int)ceil((double)strlen(arr)/(double)21)][1];
int m=0;int n=0;
for (int i=0; i<strlen(arr); i++) {
    smallArr[m][i]=arr[i];
    arrSisze[m][0]=(i+1)-n;
    if ((i-n)==19) {
        m++;
        n+=20;
    }
}
like image 996
George L Avatar asked Dec 06 '25 07:12

George L


1 Answers

1) Using memcpy

char myname[] = "hello";
char dest[20] = {0};    
/* using memcpy to copy string: */
 memcpy ( dest, myname, 5);

2) using strncpy

char str1[]= "To be or not to be";
char str2[40];

strncpy ( str2, str1, sizeof(str2) );
like image 189
shivakumar Avatar answered Dec 07 '25 21:12

shivakumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!