c++ - 单程搜索和替换

标签 c++ c performance

有谁知道如何在文本中进行一次搜索和替换?我正在开发一个高性能程序,其中每个微优化都很重要。以下是说明我目前所做工作的示例:

#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() 中列出的转义字符)。

最佳答案

您可以使用哈希表来存储所有 <from,to> 对并遍历字符串一次。

对于每个字符,检查它是否存在于哈希表中,如果存在则替换它。

它将一次完成任务。

关于c++ - 单程搜索和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18299716/

相关文章:

c++ - Visual Studio : hotkey/way to automatically sort functions in . h 与.cpp保持一致

c++ - 基本使用类来执行基本的定量生物学

c++ - fstream 替换文件的一部分

Java获取可用内存

c++ - 带有内存集的 EXC_BAD_ACCESS

c - 在C中将PPM从RGB转换为HSL

c - 从 arduino 上传入的蓝牙序列中提取值

c - C语言对字符串和文件的快速排序

performance - 使用 Jmeter 的 JBOSS wildfly 10 性能调优

performance - 如何通过缓冲加速 Haskell IO?