Copy string data with NULL character inside string to char array

好久不见. 提交于 2019-12-11 19:52:30

问题


I am trying to copy one string to char array, string have multiple NULL character. My problem is when first NULL character encountered my program stops copying the string.

I have used two approaches. This is what I am so far.

#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;
}

This program should print Hello World. How are you?. Please help me to correct this.


回答1:


Use std::copy:

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

followed by std::replace:

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

You may want to define your character array so that it is full of zeros at the start:

char resp[2000] = {};



回答2:


You could also one-shot it with

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

Of course as @Mats has mentioned your string doesn't have any null chars, strings can also be initialized as follows though:

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

C++14 has a std::string literal operator

std::string str = "Hello World.\0 How are you?"s;


来源:https://stackoverflow.com/questions/22907430/copy-string-data-with-null-character-inside-string-to-char-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!