将字符串内带有 NULL 字符的字符串数据复制到字符数组

Copy string data with NULL character inside string to char array

本文关键字:字符 字符串 数据 复制 数组 NULL      更新时间:2023-10-16

我正在尝试将一个字符串复制到字符数组,字符串有多个 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] = {};