【发布时间】:2012-07-16 23:41:51
【问题描述】:
假设我要生成------,只有-,有没有C宏可以生成重复字符串?
【问题讨论】:
-
是:stackoverflow.com/a/10542793/726361 并记住并排放置的字符文字会自动连接。
-
在我的键盘上,您只需按住键即可。不需要宏。
假设我要生成------,只有-,有没有C宏可以生成重复字符串?
【问题讨论】:
是和不是。这并不简单,通常也不是一个好主意,但您可以为有限的、恒定的大小和恒定的字符执行此操作。使用 C 预处理器有很多方法可以做到这一点。这是一个:
#define DUP(n,c) DUP ## n ( c )
#define DUP7(c) c c c c c c c
#define DUP6(c) c c c c c c
#define DUP5(c) c c c c c
#define DUP4(c) c c c c
#define DUP3(c) c c c
#define DUP2(c) c c
#define DUP1(c) c
#include <stdio.h>
int main(int argc, char** argv)
{
printf("%s\n", DUP(5,"-"));
printf("%s\n", DUP(7,"-"));
return 0;
}
它并不漂亮,只有当您真的希望将字符串存储为静态(常量)数据时才有用。 n 和DUP 的'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;
}
或者,按照@Jack 的建议使用memset。
【讨论】:
DUP 宏很聪明,尽管我同意这不是一个好主意。
dupchar 函数中:必须检查s 是否为非NULL 值;我认为您可以在循环语句的第一个参数中添加关于变量声明的注释是 C99 特性;将c 视为char 不是一个好主意。必须使用int 代替。
int 值填充char* 数组呢?
malloc 并且具有可变范围的for 循环的函数。
不在 C 标准中。您需要编写自己的实现。
编辑:
类似这样的:
#include <stdio.h>
#include <string.h>
#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;
}
【讨论】:
memset 似乎是最干净的解决方案。
使用提升,例如
#include <stdio.h>
#include <boost/preprocessor/repetition/repeat.hpp>
#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;
}
【讨论】: