将整数数组转换为字符数组

13

我有一个整数数组,例如 int example[5] = {1,2,3,4,5}。现在我想使用C将它们转换为字符数组,而不是C++。我该如何做?


2
1,2,3,4,5 代表什么?您期望有哪些合理的转换?请在问题中添加一个示例。 - Aamir
这是一个打字错误...应该是 int example[5]。 - CrazyCoder
@winbros - 你想要的字符数组是像 {'1','2','3','4','5'} 这样的吗? - Sachin Shanbhag
你想处理ASCII码的1,2...吗? - Javed Akram
5个回答

10

根据您的实际需求,这个问题有几种可能的答案:

int example[5] = {1,2,3,4,5};
char output[5];
int i;

直接复制会产生ASCII控制字符1-5

for (i = 0 ; i < 5 ; ++i)
{
    output[i] = example[i];
}

数字字符 '1' - '5'

for (i = 0 ; i < 5 ; ++i)
{
    output[i] = example[i] + '0';
}

表示1到5的字符串。

char stringBuffer[20]; // Needs to be more than big enough to hold all the digits of an int
char* outputStrings[5];

for (i = 0 ; i < 5 ; ++i)
{
    snprintf(stringBuffer, 20, "%d", example[i]);
    // check for overrun omitted
    outputStrings[i] = strdup(stringBuffer);
}

6
如果整数大于'9'怎么办?大于10的整数不会被转换为字符格式。 - Alston

3
#include <stdio.h>

int main(void)
{
    int i_array[5] = { 65, 66, 67, 68, 69 };
    char* c_array[5];

    int i = 0;
    for (i; i < 5; i++)
    {   
        //c[i] = itoa(array[i]);    /* Windows */

        /* Linux */
        // allocate a big enough char to store an int (which is 4bytes, depending on your platform)
        char c[sizeof(int)];    

        // copy int to char
        snprintf(c, sizeof(int), "%d", i_array[i]); //copy those 4bytes

        // allocate enough space on char* array to store this result
        c_array[i] = malloc(sizeof(c)); 
        strcpy(c_array[i], c); // copy to the array of results

        printf("c[%d] = %s\n", i, c_array[i]); //print it
    }   

    // loop again and release memory: free(c_array[i])

    return 0;
}

输出:

c[0] = 65
c[1] = 66
c[2] = 67
c[3] = 68
c[4] = 69

1
你的答案只适用于小于等于999的数字,超过这个范围它将开始截断数字 - 32位2补码整数的INT_MAX为2147483647,这比3位数字要多得多(其中一个是由'\0'占据的)。 - JeremyP

1

您可以使用以下表达式将单个数字整数转换为相应的字符:

int  intDigit = 3;
char charDigit = '0' + intDigit;  /* Sets charDigit to the character '3'. */

请注意,这仅适用于单个数字。将上述方法推广到数组应该很容易。

0
你需要创建数组,因为sizeof(int)(几乎肯定)与sizeof(char)==1不同。
在循环中执行char_example[i] = example[i]
如果你想要将一个整数转换为字符串,你可以简单地将该整数与字符'0'相加。但是,前提是你确定这个整数在0和9之间。否则,你就需要使用一些更复杂的方法,比如sprintf函数。

0

在纯C中,我会这样做:

char** makeStrArr(const int* vals, const int nelems)
{
    char** strarr = (char**)malloc(sizeof(char*) * nelems);
    int i;
    char buf[128];

    for (i = 0; i < nelems; i++)
    {
        strarr[i] = (char*)malloc(sprintf(buf, "%d", vals[i]) + 1);
        strcpy(strarr[i], buf);
    }
    return strarr;
}

void freeStrArr(char** strarr, int nelems)
{
    int i = 0;
    for (i = 0; i < nelems; i++) {
        free(strarr[i]);
    }
    free(strarr);
}

void iarrtostrarrinc()
{
    int i_array[] = { 65, 66, 67, 68, 69 };
    char** strarr = makeStrArr(i_array, 5);
    int i;
    for (i = 0; i < 5; i++) {
        printf("%s\n", strarr[i]);
    }
    freeStrArr(strarr, 5);
}

一个malloc-cast不是“纯C”,它是C ++。 - user411313

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接