将字符从字符串复制到C中的另一个字符串

标签 c string char truncate strncpy

我有一个字符串 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 .. 如何获得摆脱那个?或者如何让它以其他方式工作?任何建议将不胜感激。

最佳答案

首先,您需要为 \0 添加 +1 大小。

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

关于将字符从字符串复制到C中的另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10375728/

相关文章:

java - 将 Char 转换为 double

c++ - 如何将字符串解析为 ctime 结构?

java - "Must be of an array type but is resolved to string"....为什么以及如何修复它?

c - 计算平均值的程序 : if to test chars

python - 为什么该字符串没有更改为大写

java - 如何通过在java中占用空间来拆分String

C 编程 - 调用 fgets() 两次?

java - 在 if 语句中使用按位 &

android - Android 的 bluez 和服务/特性缓存问题

c - 在哪里可以获得 CRC(循环冗余校验)代码?