Sunday, 15 May 2011

c - Replace specific char in char * -



c - Replace specific char in char * -

i want replace char newline. here code:

char *string = readresource(); //returns pointer array using memcpy() char *finalstring = string; for(int x=0; x< int(sizeofres); x++) { if (string[x] == char(84)) finalstring[x] = here want newline; else finalstring[x] = string[x]; }

i know char * read-only since pointer array stored in memory using finalstring[x] = '\n'; doesn't work.

but can't strcpy() array either because contains null bytes.

is there simple way accomplish this?

use memcpy() if array contains null characters.

a basic programme 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); homecoming 0; }

c

No comments:

Post a Comment