在C语言中,我如何将一个整数转换成字符串? [英] In C, how do i insert an integer into a string?

查看:270
本文介绍了在C语言中,我如何将一个整数转换成字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的code得到字符的字符串。例如,aaabbdddd
函数插入一个新的字符串的字母和时代出现的数量。所以输出为这个特定的字符串应该是a3b2d4。
我的问题是我怎么插入数字到字符串?我尝试使用itoa它转换的整个字符串转换成一个数字。
这里是我的code:

My code gets a string of characters. For example "aaabbdddd" A function inserts to a new string the letters and the amount of times they appear. So the output for this specific string should be "a3b2d4". My question is how do I insert the numbers into the string? I tried using itoa and it converted the entire string into a single number. Here's my code:

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

我认为这个问题是在该行shorttxt [J + 1] =计数;因为这就是我想要把INT到字符串。

I believe that the problem is in the line "shorttxt[j + 1] = count;" because thats where I want to put the int into the string.

推荐答案

您是对的,问题是该行:

You are right, the problem is the line:

shorttxt[j + 1] = count;

将其更改为:

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

和你应该罚款。

的原因是不希望的串本身的数量,但该字符重新presenting数。添加ASCII值的字符0的实际人数为您提供了正确的结果。

The reason is that you don't want the number itself in the string, but the character representing the number. Adding the ascii value for the character 0 to the actual number gives you the correct result.

这篇关于在C语言中,我如何将一个整数转换成字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆