2013-12-11 34 views
-4

給定一個字符串"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」

+1

在您設想精確調用速度很慢之前,會對您的程序進行基準測試。另外,C和C++是不同的語言。選一個! (如果您選擇C++,請確保使用[C++ 11](http://en.wikipedia.org/wiki/C%2B%2B11))。 –

+0

C和C++的解決方案將有所不同。選一個。 –

+0

我已經改變了問題,我會再發帖嗎? – liumilan

回答

2

這裏有讓你在C右腳++

  1. 將步驟你的字符串中std::string
  2. 使用std::string::find發現「{ 「
  3. 再次使用std::string::find,找到」}「,後面跟着在步驟2中找到的」{「
  4. 使用std::string::erase使用從步驟2中得到的信息和第3步

一旦你有去,你可以運行它,看看速度高效地爲你所需要的刪除字符,然後你可以根據瓶頸是什麼進行優化。

0

效率可以指易於編碼,維護成本或執行速度。通常你想罷工3

之間的平衡,因爲你明確提到串,我想你指的C++,不C.

在當前的C++環境下,在一個字符串替換「東西」可以很容易地用string :: replace來完成,或者用正則表達式(本身是一個主題)來完成。

如果您希望某些難以維護但可能更快的內容,則可以遍歷字符串並根據需要插入或刪除字符。