給定一個字符串"abc{efg}dgb"
,我想對大括號之間的字符進行替換。這是我目前正在嘗試的。但它需要memcpy
3次。可以改進嗎?如何替換字符?
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<string>
#include<iostream>
#include<string.h>
using namespace std;
void replace(char *newWord,char *a,char *b)
{
char *p;
char *q;
int offset = 0;
int pos = 0;
int len_b = strlen(b);
p= strchr(a,'{');
offset = p -a;
memcpy(newWord,a,offset);
offset += pos;
memcpy(newWord+offset,b,len_b);
offset += len_b;
q = strchr(a,'}');
memcpy(newWord+offset,q+1,strlen(q+1));
}
int main()
{
char *a = "abc{acd}efg";
char *b = "new";
char *q;
char newWord[1024]="";
replace(newWord,a,b);
printf("%s",newWord);
}
現在newWord是 「abcnewefg」
在您設想精確調用速度很慢之前,會對您的程序進行基準測試。另外,C和C++是不同的語言。選一個! (如果您選擇C++,請確保使用[C++ 11](http://en.wikipedia.org/wiki/C%2B%2B11))。 –
C和C++的解決方案將有所不同。選一個。 –
我已經改變了問題,我會再發帖嗎? – liumilan