3

我有一个字符串 AAbbCC 我需要的是复制前两个并将它们添加到数组中,然后复制中间两个并将它们添加到数组中,最后复制最后两个并将它们添加到数组中。

这就是我所做的:

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

它通过了前一个中的那些 bb 和 AA .. 即使数组只有两个位置,当我使用 strtol 时,它给了我一些很大的价值,而不是我正在寻找的 187 .. 如何摆脱它? 或者如何让它以其他方式工作?任何意见,将不胜感激。

4

2 回答 2

5

首先,您需要为\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

我希望这对你有帮助。

更新

您可以编写一个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);
于 2012-04-29T20:47:39.820 回答
1

Well, color1 and color2 are two bytes long - you have no room for the \0 terminator. When you look at one of them as a string, you get more characters that you wished for. If you look at them as two characters, you'll get the right result.

You should define them as 3 characters long and put the \0 at the end.

于 2012-04-29T20:35:56.063 回答