简体   繁体   中英

Replace specific char in char *

I want to replace a certain char with a newline. Here is my code:

char *string = ReadResource(); //returns pointer to array using memcpy()
char *FinalString = string;   
for(int x=0; x< int(SizeOfRes); x++)
      {
          if (string[x] == char(84)) 
            FinalString[x] = HERE DO I WANT A NEWLINE;

          else 
            FinalString[x] = string[x];
      }

I know that char * is read-only since this is a pointer to an array stored in the memory so using FinalString[x] = '\\n'; doesn't work.

But I can't strcpy() the array either because it contains NULL bytes.

Is there a simple way to achieve this?

Use memcpy() if your array contains NULL characters.

A basic program which works :

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

int main(int argc, char *argv[])
{
  char *cbuffer = "hello \x00world";
  char buffer[12];
  memcpy((void *)buffer, (void *)cbuffer, 12);
  buffer[2] = 'h';  
  ofstream ofs ("nullfile.bin", ios::binary);
  ofs.write(buffer,12);
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM