魔兽私服中,你是否遇见很多玩家互相说脏话什么的,批评GM什么的。
当然,你也希望能过滤掉这些说话的内容。下面的这个函数就是过滤用的
std::string swearingReplacement(std::string str, std::string oldStr, const std::string newStr)
需要过滤的词语 过滤前的语句 过滤后的语句
这个就是诅咒,咒骂过滤系统
看看完整的函数。
std::string swearingReplacement(std::string str, std::string oldStr, const std::string newStr)
{
typedef UNORDERED_MAP<char, size_t> FillerCharContainer;
FillerCharContainer m_FillerCharContainer;
size_t pos = 0;
// This sting will keep original case (capitals etc..)
std::string filteredString = str;
// the str string will be lowercase. To make matching easier from database
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
// Oldstr must search for lower case only, as that is what the string we are searching trough is.
std::transform(oldStr.begin(), oldStr.end(), oldStr.begin(), ::tolower);
for (std::string::iterator itr = str.begin(); itr != str.end(); ++itr)
{
if (ispunct(*itr) || isspace(*itr))
m_FillerCharContainer.insert(std::make_pair<char, size_t>(*itr, pos));
++pos;
}
for (FillerCharContainer::const_iterator itr1 = m_FillerCharContainer.begin(); itr1 != m_FillerCharContainer.end(); ++itr1)
{
str.replace(itr1->second, 1, "");
filteredString.replace(itr1->second, 1, "");
}
pos = 0;
// We loop the lowercase string.
while((pos = str.find(oldStr, pos)) != std::string::npos)
{
size_t oldPos = pos;
// We replace equally in both strings, so they keep in sync on next iteration (if any next iteration).
str.replace(pos, oldStr.length(), newStr);
filteredString.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
for (FillerCharContainer::iterator itr2 = m_FillerCharContainer.begin(); itr2 != m_FillerCharContainer.end();)
{
if (itr2->second >= oldPos + oldStr.length())
itr2->second += newStr.length() - oldStr.length();
size_t punctPos = itr2->second;
if (punctPos > oldPos && punctPos < oldPos + oldStr.length())
itr2 = m_FillerCharContainer.erase(itr2);
else
++itr2;
}
}
for (FillerCharContainer::const_iterator itr3 = m_FillerCharContainer.begin(); itr3 != m_FillerCharContainer.end(); ++itr3)
filteredString.insert(filteredString.begin() + itr3->second, itr1->first);
return filteredString;
}
这个就是一个独立的函数,你得需要基本的C++知识。然后把函数加到你的代码中,就可以使用了!!
具体怎么使用,自己就多考虑考虑了
下面是完整代码下载
|