ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c-通过串联另一个char *来初始化const char *

2019-10-13 13:07:51  阅读:28  来源: 互联网

标签:c concatenation initialization const-char


我想重构:

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

变成类似:

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

因为在许多其他地方都使用了字符串“ quick”.理想情况下,我只需要能够使用const基本类型来做到这一点,所以不需要字符串.做这个的最好方式是什么?

解决方法:

以答案的形式汇编评论:

>使用宏.

#define QUICK "quick "

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

>使用std:string.

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

工作代码:

#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

标签:c,concatenation,initialization,const-char
来源: https://codeday.me/bug/20191013/1907947.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有