Linux下的C语言实现#separator.join(array)


=Start=

缘由:

C语言中如何将 整数类型数组 中的数字放入一个字符串中(方便打印),类似于Python中的:

int_array_str = ' '.join(str(e) for e in int_array)

正文:

参考解答:
#include <stdio.h>
/*
C语言中将 整数类型数组 中的数字放在一个字符串中打印出来
    linux c concat int array as string
https://stackoverflow.com/questions/30234363/how-can-i-store-an-int-array-into-string
https://stackoverflow.com/questions/15192221/concatenating-array-of-integers-in-c/15192458#15192458
https://stackoverflow.com/questions/3902640/c-concatenate-int
*/
int main(void)
{
    int a[5]={5, 21, 456, 1, 3};
    char s[128] = {0};
    char s2[128] = {0};
    int i, n = 0;
 
    printf ("\n int a[5] = ");
 
    for (i = 0, n = 0; i < 5; i++) {
        printf("%d ", a[i]);
        n += sprintf (&s[n], "%d", a[i]);
        if(i < 4)
            n += sprintf (&s[n], "%c", '\t');
    }
    printf ("\n\n char* s = %s\n\n", s);
 
    for (i = 0, n = 0; i < 5; i++) {
        n += snprintf (&s2[n], 128-n, "%d", a[i]);
        if(i < 4)
            n += sprintf (&s2[n], "%c", '\t');
    }
    printf ("\n\n char* s2 = %s\n\n", s2);
 
    return 0;
}

主要是利用sprintf/snprintf函数将整数转换成字符串并存入字符数组中,需要根据sprintf/snprintf函数的返回值决定数字在字符数组中的位置

参考链接:

https://stackoverflow.com/questions/30234363/how-can-i-store-an-int-array-into-string
https://stackoverflow.com/questions/15192221/concatenating-array-of-integers-in-c/15192458#15192458
https://stackoverflow.com/questions/3902640/c-concatenate-int

https://stackoverflow.com/questions/308695/how-do-i-concatenate-const-literal-strings-in-c

=END=

, ,

《“Linux下的C语言实现#separator.join(array)”》 有 1 条评论

  1. Linux的C语言中字符串连接可以用strcat/strncat函数实现
    https://stackoverflow.com/questions/308695/how-do-i-concatenate-const-literal-strings-in-c
    http://man7.org/linux/man-pages/man3/strcat.3.html
    `
    char str[80] = “\0”;
    strcat(str, “these “);
    strcat(str, “strings “);
    strcat(str, “are “);
    strcat(str, “concatenated.”);
    `
    Linux的C语言中将整数转换成字符串(反过来有atoi/strtol)
    https://stackoverflow.com/questions/9655202/how-to-convert-integer-to-string-in-c
    https://stackoverflow.com/questions/8257714/how-to-convert-an-int-to-string-in-c
    http://man7.org/linux/man-pages/man3/sprintf.3.html
    `
    sprintf/snprintf
    `

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注