通过连接另一个char来初始化const char *

时间:2014-11-07 18:31:46

标签: c++ initialization concatenation const-char

我想重构:

const char* arr = 
  "The "
  "quick "
  "brown";

成像:

const char* quick = "quick ";
const char* arr = 
  "The "
  quick
  "brown";

因为使用字符串“quick”是很多其他地方。理想情况下,我需要能够使用const原始类型来执行此操作,因此不需要字符串。这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:3)

以答案形式编辑评论:

  1. 使用宏。

    #define QUICK "quick "
    
    char const* arr = "The " QUICK "brown";
    
  2. 使用std:string

    std::string quick = "quick ";
    std::string arr = std::string("The ") + quick + "brown";
    
  3. 工作代码:

    #include <iostream>
    #include <string>
    
    #define QUICK "quick "
    
    void test1()
    {
       char const* arr = "The " QUICK "brown";
       std::cout << arr << std::endl;
    }
    
    void test2()
    {
       std::string quick = "quick ";
       std::string arr = std::string("The ") + quick + "brown";
       std::cout << arr << std::endl;
    }
    
    int main()
    {
       test1();
       test2();
    }
    

    输出:

    The quick brown
    The quick brown