C 编程语言中没有字符串操作,不像您的代码所暗示的那样。在表达式“const char* ChosenFruit = ...”中,您告诉编译器您想要将包含“Chosen Fruit”的数组的地址与 FruitsList 中第三个字符串的地址(您将其截断为'char' 因为类型转换),并将结果分配给 ChosenFruit。ChosenFruit 只是指向内存中很可能不包含可打印字符的某个遥远位置。
要在 C 中连接两个字符串,您必须分配一个足够大的新数组来保存结果,并显式复制两个字符串的字符。您可以使用“strcpy()”和“strcat()”函数进行复制:
const char* s1 = "Hello ";
const char* s2 = "world!";
char s3[32]; /* big enough to hold s1 and s2 */
strcpy( s3, s1 ); /* copy s1 to s3 */
strcat( s3, s2 ); /* copy s1 to end of s3 */
你可以在 C++ 中做同样的事情,但是使用 C++ 标准库中的“std::string”对象可以说是更安全和更好的做法。'std::string' 对象自动分配从堆中保存字符串所需的内存量,在不再需要时自动释放此内存,并实现一个版本的 '+' 运算符来满足您的需求(级联):
#include <string>
static const std::string Fruits[] = { "Mango", "Apple", "Pear", "Banana" };
static const std::string Prefix = "Chosen Fruit ";
std::string ChosenFruit = Prefix + Fruits[index];
表达式“ChosenFruit = Prefix + ...”的意思是“调用以两个 'std::string' 对象作为参数的 '+' 运算符的版本”。此“+”运算符连接两个字符串并返回包含结果的新“std::string”对象。