【问题标题】:Modify the self-made concat function so it will accept more than two arguments修改自制的 concat 函数,使其接受两个以上的参数
【发布时间】:2012-02-09 15:55:53
【问题描述】:

我编写了一个自制的concat函数:

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

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

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

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

【问题讨论】:

  • C 还是 C++?这是高度相关的。
  • 不简单,但你可以使用 var_args 类型输入。快门。
  • 如果你知道一种适用于 C++ 但不适用于 C 的方法,它仍然很有趣......
  • @JakeBadlands:在真正的 C++ 程序中使用的绝大多数技术在 C 中都行不通。这两种语言是不同的语言;请说明您使用的是哪一个。
  • 大声笑 - 这里还是早上,我还没有喝咖啡 :)

标签: c++ c char


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您正在寻找的功能是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");
    

    【讨论】:

    • 不幸的是,这不起作用。当我尝试这样的事情时:char buf[BUFSIZ]; strcpy(buf, concat(2, "hello", " world")); 在运行时出现错误 EXC_BAD_ACCESS。错误行是char* pValue = va_arg(ap, char*);
    • @JakeBadlands 您只能修改可写内存,而字符串文字不能。你必须:char h[6] = "hel"; concat(2, h, "lo");
    • 我已将“分配缓冲区”这一行更改为char* pFinal = (char *) malloc (BUFSIZ);。现在,当我尝试 char h[BUFSIZ]="hel"; concat(2, h, "lo"); 时,h 包含“hel”而它应该包含“hello”
    【解决方案3】:

    很简单:

    #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
    

    当然,你可以添加一些重载来提高效率。

    【讨论】:

      猜你喜欢
      • 2014-02-08
      • 2015-05-11
      • 2018-08-26
      • 2012-10-22
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      • 1970-01-01
      • 2018-04-20
      相关资源
      最近更新 更多