在 C 语言中连接字符串和 Int
本文将演示在 C 语言中连接 string 和 int 的多种方法。
使用 asprintf、strcat 和 strcpy 函数来连接 C 语言中的字符串和整数
连接 int 变量和字符串的第一步是将整数转换成字符串。我们利用 asprintf 函数将传来的整数存储为一个字符字符串。asprintf 是 GNU C 库扩展的一部分,在其他实现中可能无法使用。它的工作原理与 sprintf 类似,只是目标字符串缓冲区是通过内部调用 malloc 函数动态分配的,返回的指针应该在程序退出前释放。整数转换完成后,我们连锁调用 strcpy 和 strcat,在用户分配的缓冲区中连通两个给定的字符串。在本例中,我们任意定义了 MAX 宏来表示目标缓冲区的大小,但在实际场景中,使用 malloc 会更加灵活。
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef MAX
#define MAX 100
#endif
int main(int argc, char *argv[]) {
const char *str1 = "hello there";
int n1 = 1234;
char *num;
char buffer[MAX];
if (asprintf(&num, "%d", n1) == -1) {
perror("asprintf");
} else {
strcat(strcpy(buffer, str1), num);
printf("%s\n", buffer);
free(num);
}
exit(EXIT_SUCCESS);
}
输出:
hello there1234
或者,在链式调用之后,可以再调用一次 strcat 函数,将其他字符串追加到给定的 char 缓冲区。注意,我们检查 asprintf 函数是否成功返回值,如果失败,则继续进行连接过程。
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef MAX
#define MAX 100
#endif
int main(int argc, char *argv[]) {
const char *str1 = "hello there";
int n1 = 1234;
char *num;
char buffer[MAX];
if (asprintf(&num, "%d", n1) == -1) {
perror("asprintf");
} else {
strcat(strcpy(buffer, "Hello there, "), num);
strcat(buffer, "! continued");
printf("%s\n", buffer);
free(num);
}
exit(EXIT_SUCCESS);
}
输出:
Hello there, 1234! continued
在 C 语言中使用 asprintf 和 memccpy 函数来连接字符串和整数
另外,asprintf 可以和 memccpy 一起使用,以连接字符字符串和整数。memccpy 是 C 标准库字符串实用程序的一部分,定义在 <string.h> 头文件中。它需要两个指针表示源缓冲区和目标缓冲区。请注意,这些缓冲区的内存区域不应重叠,否则,结果将无法定义。最后两个参数代表停止复制的字符和从源位置取出的最大字节数。我们在 else 作用域中调用 free 函数,因为否则,我们无法确定 num 指针是有效指针。
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef MAX
#define MAX 100
#endif
int main(int argc, char *argv[]) {
const char *str1 = "hello there";
int n1 = 1234;
char *num;
char buffer[MAX];
if (asprintf(&num, "%d", n1) == -1) {
perror("asprintf");
} else {
memccpy(memccpy(buffer, str1, '\0', MAX) - 1, num, '\0', MAX);
printf("%s\n", buffer);
free(num);
}
exit(EXIT_SUCCESS);
}
输出:
hello there1234
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu
