2012-03-07 37 views
0

我一直有一點麻煩與我的查找和替換功能,我可以讓它取代所有字符,但我只希望它改變匹配被禁止的字的字符。發現字符串向量中的特定字符時發現C++

這裏是我到目前爲止的代碼

class getTextData 
{ 
private: 
    string currentWord; 
    vector<string> bannedWords; 
    vector<string> textWords; 
    int bannedWordCount; 
    int numWords; 
    char ch; 
    int index[3]; 
    ifstream inFile(); 
public: 
    void GetBannedList(string fileName); 
    void GetWordAmount(string fileName); 
    void GetDocumentWords(string fileName); 
    void FindBannedWords(); 
    void ReplaceWords(string fileOutput); 
}; 

for(int i = 0; i <= numWords; i++) 
{ 
    for(int j = 0; j < bannedWordCount; j++) 
    { 
     if(string::npos != textWords[i].find(bannedWords[j])) 
     {    
      textWords[i] = "***"; 
     } 
    } 
} 

這只是一個固定數量的*取代,但我想它來代替它與*不是全字匹配的字符。

在此先感謝

+0

你看過正則表達式(正則表達式)嗎? – Tim 2012-03-07 15:31:58

+0

你可以發佈'textWords'和'bannedWords'的聲明嗎? – hmjd 2012-03-07 15:32:08

+0

@hmjd我修改了我的帖子以顯示聲明。 – bobthemac 2012-03-07 15:34:07

回答

1

試試這個:

for(int i = 0; i <= numWords; i++) 
{ 
    for(int j = 0; j < bannedWordCount; j++) 
    { 
     size_t pos = textWords[i].find(bannedWords[j] 
     if(string::npos != pos)) 
     {    
      textWords[i].replace(pos, bannedWords[j].length(), 
           bannedWords[j].length(), '*'); 
     } 
    } 
} 
+0

感謝那些作品,但爲什麼'bannedWords [j] .length()'放了兩次。 – bobthemac 2012-03-07 15:44:27

+0

第一個是從舊字符串中刪除的部分的長度;第二個是放入'*'的數量。 (密集)文檔[這裏](http://www.cplusplus.com/reference/string/string/replace/) – Chowlett 2012-03-07 15:58:28

+0

沒問題,我已經知道他們做了什麼 – bobthemac 2012-03-07 16:00:46

0

使用字符串替換::(),把它的每個禁忌詞彙,並用固定字符串替換文本「*」。 語法:

string& replace (size_t pos1, size_t n1, const char* s); 
string& replace (iterator i1, iterator i2, const char* s); 
2

您可以使用std::string::replace()到一定數目的字符更改爲相同字符的多個實例:

size_t idx = textWords[i].find(bannedWords[j]); 
if(string::npos != idx) 
{    
    textWords[i].replace(idx, 
         bannedWords[j].length(), 
         bannedWords[j].length(), 
         '*'); 
} 

注意,終止外部條件for看起來可疑:

for(int i = 0; i <= numWords; i++) 

如果確切地有numWordstextWords這將訪問一個超過vector的結尾。考慮使用迭代器或從容器本身獲取要索引的容器中元素的數量:

for (int i = 0; i < textWords.size(); i++) 
{ 
    for (int j = 0; j < bannedWords.size(); j++) 
    { 
    } 
} 

而不是在其他變量中複製大小信息。

+0

+1爲終點條件的好處。 – Chowlett 2012-03-07 15:58:57

相關問題