在c++中构建/合并字符数组指针
Building / Merging character array pointers in C++
我对c++很陌生(来自c#),它让我感到困惑:S
我有一个关于数组和指针的基本问题。
如果我有下面的代码:
char * test1 = "com";
char * test2 = "ment";
我已经在一些文件中发现了类似的代码。我不太明白一个字符怎么能容纳一个字符串。但是好…
然而,我如何将这些数组连接起来才能得到"comment"
?
我很确定这个char * result = test1 + test2;
只会增加指针,然后指向内存中的某些东西,我不打算使用。
所以有可能得到一个数组像char array[] = {'c', 'o', 'm', 'm', 'e', 'n', 't'};
从这回来吗?
或者我至少可以得到一个指针指向内存中的commentNUL
之类的东西吗?
正如你所指出的,指针算术不能解决这个问题。
如果你想要一个c字符串作为结果,需要为整个新字符串分配空间,然后复制字符,通常使用strcat
/strncat
,但它们是c风格的字符串操作。
// Your C-strings
const char *test1 = "com";
const char *test2 = "ment";
// Dynamic allocation of memory for result string
char *result = new char[strlen(test1) + strlen(test2) + 1];
// Start with the empty string
*result = ' ';
// Concatenate both input strings (use strncat if you don't know
// for sure that they will fit into the result array!)
strcat(result, test1);
strcat(result, test2);
// (use result pointer)
// Free the memory after last usage
delete[] result;
在c++中,通常会尽量避免使用它们,而使用std::string
。即使您想要一个C-string作为结果,您也可以使用一个临时的std::string
来分配和管理所需的内存以及执行连接:
// Your C-strings
const char *test1 = "com";
const char *test2 = "ment";
// Wrap in temporary C++ strings and concatenate:
std::string result = std::string(test1) + std::string(test2);
// Get the pointer (only valid as long as result is in scope!)
const char *ptr = result.c_str();
此外,请注意不要将字符串字面值赋值给非const char *
指针,而应使用const char*
指针。尽量避免处理原始c字串;当然,当你使用C库时,你必须经常使用它们。
还要注意,上面提到的方法是在运行时执行的;即使编译器可以知道您想要的是什么,您也无法获得连接两个字符串字面值的编译时解决方案。我不知道你的上下文,但也许你只想有一个多行字符串文字,然后简单地放下+
,写"com" "ment"
。
c风格的解决方案可以在以下链接中找到:http://www.cplusplus.com/forum/beginner/5681/:
int len = strlen(test1)+strlen(test2);
char* result = new char[len +1]; // +1 for null terminated string
snprintf(result,len +1, "%s%s",test1,test2);
result[len] = NULL;
// use result
delete(result);
您可以使用std::string:
#include <iostream>
int main() {
// Note: the character literals are const (non const is deprecated)!
const char * test1 = "com";
const char * test2 = "ment";
// This gives a compiler error (there is no way to add pointers)
// const char * concat = test1 + test2;
// A std::string has an overload for the operator +:
std::string comment = std::string(test1) + test2;
// The dynamically allocated string.
// Note: as soon as the comment string gets altered or destroyed the
// pointer s to the internal string data (may) become invalid.
const char* s = comment.c_str();
std::cout << s << 'n';
}
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?