Linux下的C函数snprintf可以用来构建字符串,可以将不同类型的字符连接起来,下面是代码:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char dest[30] = "";
char chTest[] = "abcdfg";
int iNum = 2016;
int len = snprintf(dest, sizeof(dest), "%s@%d",chTest, iNum);
printf("%d\n", len);
printf("%s\n", dest);
return 0;
}
运行代码后,dest的内容是:abcdefg@2016,len=12;
OK,有了上面的代码,我们现在可以用变量chTest和iNum来构建任意的字符串了:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char dest[30] = "";
char chTest[] = "World!";
int iNum = 2016;
snprintf(dest, sizeof(dest), "Hello %s @Hello %d,01,01",chTest, iNum);
printf("%s\n", dest);
return 0;
}
则dest的内容为:Hello World! @Hello 2016,01,01。