是否有C宏生成重复字符串
Is there a C macro to generate repeat string?
假设我要生成只有-
的------
,是否有C宏来生成重复字符串?
使用升压,例如
#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("%sn", STRREP("-", 6));
return 0;
}
是和否。这并不简单,通常也不是一个好主意,但您可以对有限、常量大小和常量字符执行此操作。使用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("%sn", DUP(5,"-"));
printf("%sn", DUP(7,"-"));
return 0;
}
它并不漂亮,只有当您真正希望字符串存储为静态(常量)数据时才有用。n
和DUP
的'c'参数都必须是常量(它们不能是变量)。Boost.Preprocessor模块有很多关于如何以及何时使用像这样的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
。
不在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("%sn", str); //---------
return 0;
}
相关文章:
- C++-字符串是否包含一个带有简单循环的单词
- 将常量字符串添加到非常量字符串是否会给出常量字符串
- 检查字符串是否"null" C++
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 检查字符串是否为整数
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 如何检查字符串是否正确以将其转换为 int?
- 程序检查字符串是否只包含 1 和 0?
- 检查字符串是否是拉平德罗姆
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- 通过默认复制构造函数比较 C++ 字符串是否会影响性能,原因为何?
- gtest:检查字符串是否等于两个字符串之一
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 如何检查字符串是否以C++中的"ed"结尾;
- 字符串是否在其构造函数中复制数据
- 检查字符串是否是数字,然后将该数字转换为 int?
- 如何检查一个字符串是否包含多个其他字符串?
- 检查字符串是否仅包含字母
- 如何根据一个特定字母的出现来确定两个字符串是否相等?
- 查找字符串是否包含字符串向量的任何一个元素的最佳方法