【问题标题】:In C, how do i insert an integer into a string?在 C 中,如何将整数插入字符串?
【发布时间】:2015-12-03 07:42:10
【问题描述】:

我的代码得到一串字符。例如“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);
}

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

【问题讨论】:

  • 请删除c++标签。
  • 你试过我下面的答案了吗?

标签: c string int


【解决方案1】:

你是对的,问题是行:

shorttxt[j + 1] = count;

改成:

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

你应该没事的。

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

【讨论】:

  • 谢谢!有用!现在我只需要找出在想要的输出之后如何摆脱所有的胡言乱语:D
  • 太棒了!这是乱码部分的提示:C 中的字符串是零终止的。
  • 但我定义了我
  • shorttxt 未初始化,因此它是 20 个字符的垃圾。你用你的输出替换其中的一些,其余的仍然是垃圾。下面是对C字符串的介绍:eskimo.com/~scs/cclass/notes/sx8.html
【解决方案2】:

试试这段代码,它使用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);
}

【讨论】:

  • 试过了,但是程序崩溃了。当我尝试逐行调试它时,它在循环中遇到错误。
  • @user5633902 我不明白它为什么会崩溃。但请查看此链接:ideone.com/YuN2qu 它提供了正确的输出...嗯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
  • 2022-08-14
  • 1970-01-01
  • 2019-12-18
相关资源
最近更新 更多