修改自制的concat函数,使其接受两个以上的参数

Modify the self-made concat function so it will accept more than two arguments

本文关键字:参数 两个 concat 函数 修改      更新时间:2023-10-16

我已经编程了一个自制的concat函数:

char * concat (char * str1, char * str2) {
    for (int i=0; i<BUFSIZ; i++) {
        if (str1[i]=='') {
            for (int j=i; j<BUFSIZ; j++) {
                if (str2[j-i]=='') return str1;
                else str1[j]=str2[j-i];
            }
        }
    }
}

现在,如果我想连接2个以上的字符串,即buf-temp1-temp2,我必须使用类似的东西:

strcpy(buf, concat(concat(buf,temp1),temp2));

请告诉我,有没有一种简单的方法可以修改我的函数,使其接受许多参数?

在C++中,使用字符串而不是char*和函数:std::string result = std::string(buf) + temp1 + temp2;

您要查找的功能是varargs。这允许您编写一个C函数,该函数接受可变数量的参数。这就是像printf这样的功能是如何实现的

char* concat(size_t argCount, ...) {
  va_list ap;
  char* pFinal = ... // Allocate the buffer
  while (argCount) {
    char* pValue = va_arg(ap, char*);
    argCount--;
    // Concat pValue to pFinal
  }
  va_end(ap);
  return pFinal;
}

现在您可以使用可变数量的参数调用concat

concat(2, "hello", " world");
concat(4, "hel", "lo", " wo", "rld");

非常简单:

#include <string>
#include <iostream> // for the demo only
std::string concat(std::string const& a) {
  return a;
}
template <typename... Items>
std::string concat(std::string const& a, std::string const& b, Items&&... args) {
  return concat(a + b, args...);
}
int main() {
  std::cout << concat("0", "1", "2", "3") << "n";
}

在ideone:上看到它的作用

0123

当然,为了提高效率,您可以添加一些过载。