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

Is there a C macro to generate repeat string?

本文关键字:字符串 是否      更新时间:2023-10-16

假设我要生成只有-------,是否有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;
}

它并不漂亮,只有当您真正希望字符串存储为静态(常量)数据时才有用。nDUP的'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;
}