【问题标题】:How can I combine multiple char's to make a string?如何将多个字符组合成一个字符串?
【发布时间】:2013-12-25 07:41:57
【问题描述】:

我正在做字符串解析,基本上我想做的是这样的:

string signature = char[index+1] + '/' + char[index+2];

但是你不能在 char 上进行字符串连接,所以我想到了这个问题,我如何模拟 char 上的连接?

我知道 C++ 中的字符串库具有附加功能,但我认为这不适用于我的情况。有什么想法吗?

【问题讨论】:

    标签: c++ string char


    【解决方案1】:

    您可以将字符连接到std::string,您只需要将其中一个操作数设为std::string,否则您将添加整数。

    std::string signature = std::string() + char_array[index+1] + '/' + char_array[index+2];
    

    请注意,这仅在链中的第一个或第二个操作数是std::string 时才有效。这将导致对operator+ 的第一次调用返回std::string,其余的将效仿。所以这并没有给出预期的结果:

    std::string signature = char_array[index+1] + '/' + char_array[index+2] + std::string();
    

    【讨论】:

      【解决方案2】:

      在 C++11 中你实际上可以这样做:

      std::string signature{chars[index+1], '/', chars[index+2]};
      

      不确定这在实际代码中会有多大用处,但它适用于您的示例。

      【讨论】:

      • 与其他答案相比,不仅有用,而且可能是最有效的版本。 RAII
      【解决方案3】:

      除了史蒂夫和本杰明的解决方案,你还可以使用std::stringstream

      std::stringstream ss;
      ss << char_array[index + 1] << '/' << char_array[index + 2];
      std::string s = ss.str();
      

      【讨论】:

        【解决方案4】:

        您可以很容易地将字符和 C 样式字符串连接到现有字符串:

        string signature;
        
        signature += char_array[index + 1];  // append character from char_array[index+1]
        signature += '/';
        signature += char_array[index + 2];  // append character from char_array[index+2]
        

        您只需要确保++= 的左侧是std::string

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-13
          • 2019-03-22
          相关资源
          最近更新 更多