简体   繁体   中英

Initialize const char* by concatenating another char*

I want to refactor:

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

into something like:

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

because the string "quick" is used is many other places. Ideally I need to be able to do this with just const primitive types, so no string. What is the best way to do this?

Compiling the comments in the form of an answer:

  1. Use a macro.

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

     std::string quick = "quick "; std::string arr = std::string("The ") + quick + "brown"; 

Working code:

#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();
}

Output:

The quick brown
The quick brown

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM