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

时间:2015-12-03 07:42:11

标签: c string int

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

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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);
}

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

2 个答案:

答案 0 :(得分:2)

你说得对,问题就在于:

shorttxt[j + 1] = count;

将其更改为:

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

你应该没事。

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

答案 1 :(得分:0)

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

  

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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);
}