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

+0

'textWords'と' bannedWords'の宣言を投稿できますか? – hmjd

+0

@hmjd宣言を示すために投稿を修正しました。 – bobthemac

答えて

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()'を2回入れてください。 – bobthemac

+0

最初の文字列は、古い文字列から削除するセクションの長さです。 2番目は、代わりに入れられる '*'の数です。 (Dense)ドキュメント[here](http://www.cplusplus.com/reference/string/string/replace/) – Chowlett

+0

問題はありません。彼らが何をしているのかを理解しました – bobthemac

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++) 

にちょうどnumWordsがある場合、これはvectorの最後を超えてアクセスします。イテレータの使用を検討したり、コンテナ自体からインデックス化されているコンテナ内の要素の数取得:

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

ではなく、他の変数にサイズ情報を複製します。

+0

+1終了条件の良い点は+1です。 – Chowlett