I have a string AAbbCC what I need is to copy the first two and add them to an array then copy the middle two and add them to an array and finally the last two and add them to an array.
this is what I do:
char color1[2];
char color2[2];
char color3[2];
strncpy(color1, string, 2); // I take the first two characters and put them into color1
// now I truncate the string to remove those AA values:
string = strtok(string, &color1[1]);
// and when using the same code again the result in color2 is bbAA:
strncpy(color2, string, 2);
it passes those bb but also AA from previous one .. even though the array has only two places, when I use strtol on that it gives me some big value and not 187 which I'm looking for .. how to get rid of that ? or how to make it work other way? Any advice would be appreciated.
First, you need add +1 in size for the \0
.
char color1[3];
char color2[5];
and then:
strncpy(color1, string, 2);
color1[3] = '\0';
strncpy(color2, string + 2, 4);
color2[4] = '\0';
Assuming that
char *string = "AAbbCC";
printf("color1 => %s\ncolor2 => %s\n", color1, color2);
The output is:
color1 => AA
color2 => bbCC
I hope this help you.
UPDATE
You can write a substr()
function to get part of string(from x to y) and then copy to your string.
char * substr(char * s, int x, int y)
{
char * ret = malloc(strlen(s) + 1);
char * p = ret;
char * q = &s[x];
assert(ret != NULL);
while(x < y)
{
*p++ = *q++;
x ++;
}
*p++ = '\0';
return ret;
}
Then:
char *string = "AAbbCC";
char color1[3];
char color2[4];
char color3[5];
char *c1 = substr(string,0,2);
char *c2 = substr(string,2,4);
char *c3 = substr(string,4,6);
strcpy(color1, c1);
strcpy(color2, c2);
strcpy(color3, c3);
printf("color1 => %s, color2 => %s, color3 => %s\n", color1, color2, color3);
The output:
color1 => AA, color2 => bb, color3 => CC
And Don't forget:
free(c1);
free(c2);
free(c3);