有谁知道如何在文本中进行单遍搜索和替换?我正在开发一个高性能程序,其中每个微优化都很重要。以下是说明我目前所做的示例:
#include <iostream>
#include <string>
/*!
\brief Replaces all common character escape sequences with text representations
\note Some character seqences messes up the trace output and must be replaces
* with text represantions, ie. the newline character will the replaced with "\n"
* etc.
\returns The formatted string
*/
std::wstring ReplaceAll(std::wstring &str)
{
SearchAndReplace(str, L"\a", L"\\a"); // control-g, C-g
SearchAndReplace(str, L"\b", L"\\b"); // backspace, <BS>, C-h
SearchAndReplace(str, L"\t", L"\\t"); // tab, <TAB>, C-i
SearchAndReplace(str, L"\n", L"\\n"); // newline, C-j
SearchAndReplace(str, L"\v", L"\\v"); // vertical tab, C-k
SearchAndReplace(str, L"\f", L"\\f"); // formfeed character, C-l
SearchAndReplace(str, L"\r", L"\\r"); // carriage return, <RET>, C-m
return str;
}
/*!
\brief Wide string search and replace
\param str [in, out] String to search & replace
\param oldStr [in] Old string
\param newStr [in] New string
*/
std::wstring SearchAndReplace(std::wstring &str, const wchar_t *oldStr, const wchar_t *newStr) const
{
size_t oldStrLen = wcslen(oldStr);
size_t newStrLen = wcslen(newStr);
size_t pos = 0;
while((pos = str.find(oldStr, pos)) != string::npos)
{
str.replace(pos, oldStrLen, newStr);
pos += newStrLen;
}
return str;
}
int main()
{
std::wstring myStr(L"\tThe quick brown fox jumps over the lazy dog.\n\tThe quick brown fox jumps over the lazy dog\n\n");
std::wcout << L"Before replace: " << myStr;
std::wcout << L"After replace: " << ReplaceAll(myStr);
return 0;
}
上面的代码显然效率低下,因为它需要多次遍历同一个字符串。单遍搜索和替换功能应该非常灵活,以至于它可以处理要替换的不同字符数组(即不仅仅是列出的转义字符ReplaceAll()
)。