2010-04-25 36 views
1

這個特殊的任務與刪除字符串中的子字符串有關;我正在嘗試一些斯坦福大學SEE在線課程來學習一些新的語言。C++字符串操作對我來說沒有意義

到目前爲止,我已經有了下面是什麼,但如果text = "hello hello"remove ="el"時,它會停留在循環,但如果我改變文本text = "hello hllo",它的工作原理,讓我覺得我做一些明顯的愚蠢。

有一個在分配不修改輸入的字符串,而是返回一個新的字符串的規定。

string CensorString1(string text, string remove){ 
    string returned; 
    size_t found=0, lastfound=0; 
    found = (text.substr(lastfound,text.size())).find(remove); 
    while (string::npos != found){ 
     returned += text.substr(lastfound,found); 
     lastfound = found + remove.size(); 
     found = (text.substr(lastfound,text.size())).find(remove); 
    } 
    returned += text.substr(lastfound,found); 
    return returned; 
} 

指導,將不勝感激:-)感謝

UPDATE

接過給出的非常客氣的建議和修改我的代碼如下:

string CensorString1(string text, string remove){ 
string returned; 
size_t found=0, lastfound=0; 
found = text.find(remove); 
while (string::npos != found){ 
    returned += text.substr(lastfound,found); 
    lastfound = found + remove.length(); 
    found = text.find(remove,lastfound); 
} 
returned += text.substr(lastfound); 
return returned; 
} 

但還是表現的同樣

任何MO重新創意人?

回答

5

found = (text.substr(lastfound,text.size())).find(remove);不正確。它在text.substr(lastfound,text.size())中返回搜索字符串的索引,但不在text中。

你或許應該將其更改爲found = text.find(text, lastfound);

除了被不正確,走子(這意味着,分配一個新的字符串),並計算指數是非常低效的,除非優化器是超級智能。

而且,最終returned += text.substr(lastfound,found);太不正確的:你需要添加文本的最後一個塊,而不是一個,直到found指數(這是最有可能爲空,因爲lastfound可以比found更小更好的將是returned += text.substr(lastfound);

編輯:。
在第二個例子,你需要returned += text.substr(lastfound,found-lastfound);更換returned += text.substr(lastfound,found); 的第二個參數是substr長度,而不是位置

隨着這一變化,測試示例運行在我的測試程序控制罰款上午。

(由JF塞巴斯蒂安加入:)

string CensorString1(string const& text, string const& remove){ 
    string returned; 
    size_t found = string::npos, lastfound = 0; 
    do { 
    found = text.find(remove, lastfound); 
    returned += text.substr(lastfound, found-lastfound); 
    lastfound = found + remove.size(); 
    } while(found != string::npos); 
    return returned; 
} 
+0

謝謝!更新問題以反映 – Bolster 2010-04-25 18:19:10

+0

@Andrew:也已更新。 – Vlad 2010-04-25 18:37:55

+0

@Vlad,* facepalm *總是諮詢原型......謝謝,享受打勾和upvote – Bolster 2010-04-25 19:23:02

0

text.substr(lastfound,text.size())text中間的某個地方開始,並繼續爲text的整個尺寸。這是沒有道理的,儘管我認爲這是有效的,因爲這些特殊的函數處理範圍錯誤的方式很奇怪。 string::npos會比size陳述你的意圖更好。

一般來說,string的操作成員不如<algorithm>中的更一般算法那麼優雅。我建議您使用這些替代,例如std::search,以及string::iterator代替整數偏移量。

UPDATE:相同類型的錯誤的存在於第二個例子。使用string::npos作爲substr的第二個參數以獲取子字符串的結尾。

0

found = (text.substr(lastfound,text.size())).find(remove);開始爲find()功能從頭再來爲零(即最後一場比賽後的第一個字符將具有指數0,它會看起來像計數開始text)。但是,查找可以採用2個參數,其中第二個參數是要開始的索引。所以,你可以將此行更改爲found = text.find(remove,lastfound)

更清楚:

text =      hellohello 
find "el" in here   ^is at index 1 in `text` 
substring after match   lohello 
find "el" in here    ^is at index 3 in the substring 
            but your program doesn't know 
            that's actually index 6 in `text`