将字符串内带有 NULL 字符的字符串数据复制到字符数组
Copy string data with NULL character inside string to char array
我正在尝试将一个字符串复制到字符数组,字符串有多个 NULL 字符。我的问题是当遇到第一个 NULL 字符时,我的程序停止复制字符串。
我使用了两种方法。这就是我到目前为止的情况。
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
std::string str = "Hello World. How are you? ";
char resp[2000];
int i = 0;
memset(resp, 0, sizeof(resp));
/* Approach 1*/
while(i < str.length())
{
if(str.at(i) == ' ')
str.replace(str.begin(), str.begin()+i, " ");
resp[i] = str.at(i);
i++;
}
/* Approach 2*/
memcpy(resp, str.c_str(), 2000);
cout << resp << endl;
return 0;
}
此程序应打印Hello World. How are you?
。请帮助我纠正这一点。
你也可以一次性使用
std::transform(
str.begin(), str.end(), resp, [](char c) { return c == ' ' ? ' ' : c; }
);
当然,正如@Mats提到的,您的字符串没有任何空字符,字符串也可以初始化如下:
char const cstr[] = "Hello World. How are you?";
std::string str(cstr, sizeof cstr);
C++14 有一个std::string
文字运算符
std::string str = "Hello World. How are you?"s;
使用 std::copy
:
std::copy(str.begin(), str.end(), std::begin(resp));
后跟std::replace
:
std::replace(std::begin(resp), std::begin(resp) + str.size(), ' ', ' ');
您可能希望定义字符数组,使其在开头充满零:
char resp[2000] = {};
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数