在C中,如何将整数插入字符串?

我的代码获取了一串字符。 例如“aaabbdddd”函数将字母及其出现的次数插入新字符串。 因此,此特定字符串的输出应为“a3b2d4”。 我的问题是如何将数字插入字符串? 我尝试使用itoa并将整个字符串转换为单个数字。 这是我的代码:

#define _CRT_SECURE_NO_WARNINGS #include  #include  #include  #define LONG 80 #define SHORT 20 void longtext(char longtxt[LONG], char shorttxt[SHORT]) { int i, j=0, count=0, tmp; char letter; for (i = 0; i <= strlen(longtxt); ++i) { if (i == 0) { letter = longtxt[i]; ++count; } else if (letter == longtxt[i]) ++count; else { shorttxt[j] = letter; shorttxt[j + 1] = count; j += 2; count = 1; letter = longtxt[i]; } } } int main() { char longtxt[LONG] = "aaabbdddd",shorttxt[SHORT]; longtext(longtxt,shorttxt); printf("%s", shorttxt); } 

我认为问题在于“shorttxt [j + 1] = count;” 因为那是我想把int放入字符串的地方。

你说得对,问题就在于:

 shorttxt[j + 1] = count; 

将其更改为:

 shorttxt[j + 1] = count + '0'; 

而你应该没事。

原因是您不希望数字本身在字符串中,而是表示数字的字符。 将字符0的ascii值添加到实际数字可以得到正确的结果。

试试这段代码,它使用snprintf将整数转换为字符串。

注意:如果计数超过字符大小,您可能需要将大小从2增加。

 #include  #include  #include  #define LONG 80 #define SHORT 20 void longtext(char longtxt[LONG], char shorttxt[SHORT]) { int i, j=0, count=0, tmp; char letter; for (i = 0; i <= strlen(longtxt); ++i) { if (i == 0) { letter = longtxt[i]; ++count; } else if (letter == longtxt[i]) ++count; else { shorttxt[j] = letter; snprintf(&shorttxt[j + 1],2,"%d",count); j += 2; count = 1; letter = longtxt[i]; } } } int main() { char longtxt[LONG] = "aaabbdddd",shorttxt[SHORT]; longtext(longtxt,shorttxt); printf("%s", shorttxt); }