2012-03-07 35 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

相关问题