Copy character from string to another string in C

I have an AAbbCC string, what I need is to copy the first two and add them to the array, and then copy the middle of two and add them to the array and finally the last two and add them to the array.

that's what I'm doing:

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 the previous one ... although the array has only two places, when I use strtol, it gives me some big value, and not the 187 I'm looking for .. how to get rid of this? or how to make it work in another way? Any advice would be appreciated.

+3
source share
2 answers

, color1 color2 - \0. , , . , .

3 \0 .

+1

+1 \0.

char color1[3];
char color2[5];

:

strncpy(color1, string, 2);
color1[3] = '\0';

strncpy(color2, string + 2, 4); 
color2[4] = '\0';

,

char *string = "AAbbCC"; 

printf("color1 => %s\ncolor2 => %s\n", color1, color2);

:

color1 => AA
color2 => bbCC

, .

UPDATE

substr(), ( x y), .

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;
}

:

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);

:

color1 => AA, color2 => bb, color3 => CC

:

free(c1);
free(c2);
free(c3);
+4

All Articles