[英]Replace specific char in char *
我想用换行符替换某个字符。 这是我的代码:
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];
}
我知道char *
是只读的,因为这是指向内存中存储的数组的指针,因此使用FinalString[x] = '\\n';
不起作用。
但是我也不能strcpy()
数组,因为它包含NULL字节。
有没有简单的方法可以做到这一点?
如果您的数组包含NULL
字符,请使用memcpy()
。
一个有效的基本程序:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.