0

我正在尝试将一个字符串复制到 char 数组,字符串有多个 NULL 字符。我的问题是当第一个 NULL 字符遇到我的程序停止复制字符串时。

我使用了两种方法。这就是我到目前为止的情况。

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
    std::string str = "Hello World.\0 How are you?\0";
    char resp[2000];
    int i = 0;
    memset(resp, 0, sizeof(resp));
    /* Approach 1*/
    while(i < str.length())
    {
            if(str.at(i) == '\0')
            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?. 请帮我纠正这个问题。

4

2 回答 2

1

你也可以用

std::transform(
  str.begin(), str.end(), resp, [](char c) { return c == '\0' ? ' ' : c; }
);

当然,正如@Mats 提到的你的字符串没有任何空字符,字符串也可以按如下方式初始化:

char const cstr[] = "Hello World.\0 How are you?";
std::string str(cstr, sizeof cstr);

C++14 有一个std::string文字运算符

std::string str = "Hello World.\0 How are you?"s;
于 2014-04-07T09:22:41.887 回答
0

使用std::copy

std::copy(str.begin(), str.end(), std::begin(resp));

其次是std::replace

std::replace(std::begin(resp), std::begin(resp) + str.size(), '\0', ' ');

您可能想要定义您的字符数组,以便它在开始时充满零:

char resp[2000] = {};
于 2014-04-07T08:42:26.173 回答