我想要做的是制作一个由 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/