In C, how do i insert an integer into a string?

后端 未结 2 1494
春和景丽
春和景丽 2021-01-26 09:44

My code gets a string of characters. For example \"aaabbffffdd\" A function inserts to a new string the letters and the amount of times they appear. So the output for this specifi

相关标签:
2条回答
  • 2021-01-26 09:47

    You are right, the problem is the line:

    shorttxt[j + 1] = count;
    

    Change it to:

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

    And you should be fine.

    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.

    0 讨论(0)
  • 2021-01-26 10:03

    Try this code, it uses snprintf to convert integer to string.

    NOTE: You may need to increase the size from 2, if count exceeds a character size.

    #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] = "aaabbffffdd",shorttxt[SHORT];
        longtext(longtxt,shorttxt);
        printf("%s", shorttxt);
    }
    
    0 讨论(0)
提交回复
热议问题