c - 向 int 字符串添加前缀

标签 c string char int

是否有一个函数可以将 int num = 12; 之类的内容转换为字符串。

基本上我有一个存储字符串的循环。该字符串的前缀必须是int num。其中 num 每次执行一次循环迭代时都会不断增加

我想向 hello world 的原始字符串添加前缀,以便输出看起来像 12。 Hello World

char *original = "Hello world";
char *dot_space = ". ";
int num = 0;
while (num < 200) {
    char *num_string = ""; // Some how I convert the num to a string?
    char *new_string = malloc(sizeof(char) * strlen(original) + strlen(num_string) + strlen(prefix) + 1;
    strcpy(new_string, num_string);
    strcpy(new_string, prefix);
    strcpy(new_string, original);
    printf("%s\n", new_string);

    num++;
}

最佳答案

您可以使用sprintf来创建连接字符串。当然,诀窍是知道数字的长度。好吧,我们可以使用本地数组,然后将其复制到最终的字符串。

类似的东西

// reserve 4 characters for each octet in the `int`
char num_string[sizeof num * CHAR_BIT / 2];

// sprintf returns the length of the string!
int num_len = sprintf(num_string, "%d", i);

// size of char is exactly 1
char *new_string = malloc(strlen(original) + strlen(prefix) + num_len + 1);

// then concatenate all with one sprintf
sprintf(new_string, "%s%s%s", num_string, prefix, original);
<小时/>

当然,如果你足够幸运能够使用 Glibc 并使用 Linux;或者也许是 BSD,并且不介意编写可移植的到处,您可以只使用 asprintf:

// must be before the include
#define _GNU_SOURCE
#include <stdio.h>

char *new_string;
asprintf(&new_string, "%d%s%s", i, prefix, original);

这对应于上面的 4 行。

<小时/>

请注意,您最初的 strcpy x3 方法也会失败; strcpy 总是从目标缓冲区中的第一个字符开始覆盖;调用应该是 strcpystrcatstrcat

关于c - 向 int 字符串添加前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52269568/

相关文章:

无法创建整数数组来保存字符

python - 将字符串转换为 float - python

java - 为什么 char[] 优于 String 作为密码?

c - 返回对 C 中函数指针的调用

c++ - 从 Linux Makefile 打开终端

c - 扩展结构

java - 在 Java 中将 Set<Integer> 转换为 Set<String>

Javascript如何获取字符串的前三个字符

c++ - C++中字符数组的意外输出

c++ - 不推荐从字符串文字到 char* 的转换