![](/img/trans.png)
[英]substitute string character with a character from another string in C language
[英]copy character from string to another string in C
我有一個字符串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
我希望這對你有幫助。
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);
好了, color1
和color2
是兩個字節長-你有沒有空間\\ 0終結。 當您將其中一個視為字符串時 ,您會獲得更多您想要的字符。 如果你把它們看作兩個字符,你就會得到正確的結果。
您應該將它們定義為3個字符長,並將\\ 0放在最后。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.