C++ 找到c+时替换字符串向量中的特定字符+;
我的查找和替换功能遇到了一些问题,我可以让它替换所有字符,但我只希望它更改与禁用单词匹配的字符 这是到目前为止我的代码C++ 找到c+时替换字符串向量中的特定字符+;,c++,vector,replace,find,C++,Vector,Replace,Find,我的查找和替换功能遇到了一些问题,我可以让它替换所有字符,但我只希望它更改与禁用单词匹配的字符 这是到目前为止我的代码 class getTextData { private: string currentWord; vector<string> bannedWords; vector<string> textWords; int bannedWordCount; int numWords; char ch;
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] = "***";
}
}
}
类getTextData
{
私人:
字符串当前字;
矢量横幅词;
向量文本词;
int BANDWORDCOUNT;
国际货币基金组织;
char ch;
int索引[3];
ifstream-infle();
公众:
作废GetBannedList(字符串文件名);
void GetWordAmount(字符串文件名);
void GetDocumentWords(字符串文件名);
void FindBannedWords();
void ReplaceWords(字符串文件输出);
};
对于(int i=0;i使用string::replace(),为每个禁止的单词调用它,并用固定字符串“*”替换文本。
语法:
使用string::replace(),为每个禁止的单词调用它,并将文本替换为固定字符串“*”。
语法:
试试这个:
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(), '*');
}
}
}
for(inti=0;i试试这个:
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(), '*');
}
}
}
for(int i=0;i可用于将特定数量的字符更改为同一字符的多个实例:
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++)
而不是复制其他变量中的大小信息。您可以使用将特定数量的字符更改为同一字符的多个实例:
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++)
而不是复制其他变量中的大小信息。您看过正则表达式(regex)了吗?你能发布textWords
和bannedWords
的声明吗?@hmjd我已经修改了我的帖子以显示声明。@蒂姆我刚刚看过正则表达式,但我不确定它是如何工作的。你看过正则表达式(regex)了吗?你能发布textWords
和bannedWords
的声明吗?@hmjd我已经修改了我的帖子以显示声明。@蒂姆,我刚刚看过正则表达式,但我不确定它是如何工作的,谢谢,但为什么bannedWords[j].length()
放入两次。第一个是要从旧字符串中删除的节的长度;第二个是要放入的“*”的数量。(密集)文档没问题,我已经弄清楚了它们的作用是什么,但为什么是bannedWords[j]。length()
输入两次。第一个是要从旧字符串中删除的节的长度;第二个是要输入的“*”的数量。(密集)文档没问题,我已经知道它们的作用