通过串联另一个char *来初始化const char * [英] Initialize const char* by concatenating another char*
本文介绍了通过串联另一个char *来初始化const char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要重构:
const char* arr =
"The "
"quick "
"brown";
变成这样:
const char* quick = "quick ";
const char* arr =
"The "
quick
"brown";
因为在许多其他地方都使用了字符串"quick".理想情况下,我只需要能够使用const基本类型来做到这一点,所以就不需要字符串.最好的方法是什么?
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:
-
使用宏.
Use a macro.
#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
这篇关于通过串联另一个char *来初始化const char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文