是否有C宏来生成重复字符串?

假设我想生成------ ,只有- ,是否有一个C宏来生成重复的字符串?

使用提升,例如

 #include  #include  #define Fold(z, n, text) text #define STRREP(str, n) BOOST_PP_REPEAT(n, Fold, str) int main(){ printf("%s\n", STRREP("-", 6)); return 0; } 

是的,不是。 它并不简单,通常不是一个好主意,但你可以用有限的,恒定的大小和恒定的字符来做。 使用C预处理器有很多方法可以做到这一点。 这是一个:

 #define DUP(n,c) DUP ## n ( c ) #define DUP7(c) ccccccc #define DUP6(c) cccccc #define DUP5(c) ccccc #define DUP4(c) cccc #define DUP3(c) ccc #define DUP2(c) cc #define DUP1(c) c #include  int main(int argc, char** argv) { printf("%s\n", DUP(5,"-")); printf("%s\n", DUP(7,"-")); return 0; } 

它并不漂亮,只有在您真正希望将字符串存储为静态(常量)数据时才有用。 DUPn和’c’参数都必须是常量 (它们不能是变量)。 Boost.Preprocessor模块有很多关于如何以及何时(ab)使用这样的C / C ++预处理器的好信息。 虽然Boost是一个C ++库,但预处理器信息很大程度上适用于C语言。

一般来说,你在普通的C代码中做得更好:

 /* In C99 (or C++) you could declare this: static inline char* dupchar(int c, int n) in the hopes that the compiler will inline. C89 does not support inline functions, although many compilers offered (inconsistent) extensions for inlining. */ char* dupchar(int c, int n) { int i; char* s; s = malloc(n + 1); /* need +1 for null character to terminate string */ if (s != NULL) { for(i=0; i < n; i++) s[i] = c; } return s; } 

或者,使用memset ,如@Jack建议的那样。

不是C标准。你需要编写自己的实现。

编辑:

像这样的东西:

 #include  #include  #define REPEAT(buf, size, ch) memset(&buf, ch, size) int main(void) { char str[10] = { 0 }; REPEAT(str, 9, '-'); printf("%s\n", str); //--------- return 0; }