c - 另一个字符串中的字符串标识符

标签 c string

<分区>

是否可以在另一个字符串标识符中包含一个字符串标识符,并打印整个内容?例如:

int main()
{
    char *str1 = "%s says:";
    char *name = "John";
    printf("%s\n", str1, name);
    return(0);
}

我预期的输出是 John says:。我怎么会 printf 或 sprintf 这样的东西?

最佳答案

不,printf 不能那样工作。您必须在两个不同的阶段执行此操作:

const char *fmt = "%s says: ";
char result1[SIZE];             // where SIZE is large enough to hold the result
sprintf( result, fmt, "John" ); // result now contains "John says: "
printf( "%s\n", result );       // writes "John says: " to standard output 

我不得不多次对此进行修改,我需要动态构建格式字符串。这很容易。

关于c - 另一个字符串中的字符串标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38731053/

相关文章:

c++ - VC++ 中 Unicode 字符串的语法是什么?

PHP字符串替换匹配整个单词

c# - 拆分一串数字和字符

javascript - 如何在Javascript中快速从字符串生成数组

python - 完全相同的文本字符串不匹配

c - scanf 中的可选输入变量

c - 寻找我参加的旧测试的答案,试图了解我应该做什么。(也许是 Malloc 函数?)

c - 为什么夹板不解析curl/curlbuild.h?

c - 从 C 程序将 printf 写入 shell 脚本的单行控制台

c - 为什么这个 BitBlt 示例不再有效?