c - 从 C 中的多个整数创建 String(char*)

标签 c string char

我想要做的是制作一个由 4 个整数组成的字符串,中间有空格。就像在 Java 中一样:

String res = num1 + " " + num2 + " " + num3 + " " + num4;

但我不知道如何在 C 中做到这一点。

int numWords = 0;
int numLines = 0;
int numChars = 0;
int numBytes = strlen(string);
char *result = malloc(sizeof(char) * 10);
result += numWords; //doesnt work is there somekind of function in c to do this?

最佳答案

您可以使用 sprintf 将每个数字转换为字符串(如果需要,可以使用 strcat 将它们一个接一个地放置)。您应该跟踪字符串的长度以确保不会溢出。

例如:

int var = 10;
char buf[20];
sprintf(buf, "%d", var);  // buf string now holds the text 10

如果您有固定的格式和数字数量,则无需将其设置得比这复杂得多。所以如果你总是需要在四个数字之间留一个空格,你可以用一个 sprintf 和一个像 "%d %d %d %d" 这样的格式字符串(虽然这将需要更大的字符数组)。


编写一个添加到现有字符串的小型实用函数很容易,例如:

int add_to_string(char *buf, size_t sz, int num)
{
   char tmp[20];
   sprintf(tmp, " %d", num);

   size_t len = strlen(tmp) + strlen(buf) + 1; 
   if (len > sz)
      return -1;

   strcat(buf, tmp);
   return 0;
}

你可以这样调用它:

char buf[100];
sprintf(buf, "%d", 42);
add_to_string(buf, sizeof(buf), 9);
add_to_string(buf, sizeof(buf), 15);
add_to_string(buf, sizeof(buf), 8492);
add_to_string(buf, sizeof(buf), 35);
printf("String is '%s'\n", buf);

Output:
String is '42 9 15 8492 35'

关于c - 从 C 中的多个整数创建 String(char*),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15392485/

相关文章:

c - WAP 冒泡排序的 C 程序

c++ - 通过 int 变量设置 char[] 的大小

arrays - gdb : <error reading variable> in array while debugging VS code

C - 每个 math.h 头文件的 "acos()"是否不同?

c++ - 如何在 z/OS 上的 C++ 中使用 C 套接字 API

java - 如何在字符串中查找 int 值

python - 从字符串中提取字典键值

python - 将字符串中的每个字符转换为字典键

c++ - 字符串是 C++ 中的 char 吗?

c - 迭代直到遇到值的小数部分为 0