什么是有效的方法来取代一个字符的所有出现与另一个字符在std::字符串?


当前回答

我想我会使用std::replace_if()

一个简单的字符替换程序(OP要求的)可以使用标准库函数编写。

就地版本:

#include <string>
#include <algorithm>

void replace_char(std::string& in,
                  std::string::value_type srch,
                  std::string::value_type repl)
{
    std::replace_if(std::begin(in), std::end(in),
                    [&srch](std::string::value_type v) { return v==srch; },
                    repl);
    return;
}

如果输入是const字符串,则返回一个副本的重载:

std::string replace_char(std::string const& in,
                         std::string::value_type srch,
                         std::string::value_type repl)
{
    std::string result{ in };
    replace_char(result, srch, repl);
    return result;
}

其他回答

这个工作!我在书店应用程序中使用了类似的方法,其中库存存储在CSV(类似于.dat文件)中。但在单字符的情况下,意味着替换者只是一个单字符,例如'|',它必须在双引号"|"中,以避免抛出无效的转换const char。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int count = 0;  // for the number of occurences.
    // final hold variable of corrected word up to the npos=j
    string holdWord = "";
    // a temp var in order to replace 0 to new npos
    string holdTemp = "";
    // a csv for a an entry in a book store
    string holdLetter = "Big Java 7th Ed,Horstman,978-1118431115,99.85";

    // j = npos
    for (int j = 0; j < holdLetter.length(); j++) {

        if (holdLetter[j] == ',') {

            if ( count == 0 ) 
            {           
                holdWord = holdLetter.replace(j, 1, " | ");      
            }
            else {

                string holdTemp1 = holdLetter.replace(j, 1, " | ");

                // since replacement is three positions in length,
                // must replace new replacement's 0 to npos-3, with
                // the 0 to npos - 3 of the old replacement 
                holdTemp = holdTemp1.replace(0, j-3, holdWord, 0, j-3); 

                holdWord = "";

                holdWord = holdTemp;

            }
            holdTemp = "";
            count++;
        }
    } 
    cout << holdWord << endl;
    return 0;
}

// result:
Big Java 7th Ed | Horstman | 978-1118431115 | 99.85

我目前使用CentOS,所以我的编译器版本如下。c++版本(g++), c++ 98默认值:

g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Abseil StrReplaceAll怎么样?在头文件中:

// This file defines `absl::StrReplaceAll()`, a general-purpose string
// replacement function designed for large, arbitrary text substitutions,
// especially on strings which you are receiving from some other system for
// further processing (e.g. processing regular expressions, escaping HTML
// entities, etc.). `StrReplaceAll` is designed to be efficient even when only
// one substitution is being performed, or when substitution is rare.
//
// If the string being modified is known at compile-time, and the substitutions
// vary, `absl::Substitute()` may be a better choice.
//
// Example:
//
// std::string html_escaped = absl::StrReplaceAll(user_input, {
//                                                {"&", "&amp;"},
//                                                {"<", "&lt;"},
//                                                {">", "&gt;"},
//                                                {"\"", "&quot;"},
//                                                {"'", "&#39;"}});

Std::string不包含这样的函数,但你可以使用独立的替换函数从算法头。

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

这不是标准库中缺少的唯一方法,它本来是低级别的。 这个用例和许多其他用例由通用库涵盖,例如:

波科 绳降 提高 QtCore

QtCore & QString有我的偏好:它支持UTF8,使用更少的模板,这意味着可以理解的错误和更快的编译。它使用了“q”前缀,使命名空间变得不必要,并简化了头文件。 Boost经常生成可怕的错误消息和缓慢的编译时间。 POCO似乎是一种合理的妥协。

老派:-)

std::string str = "H:/recursos/audio/youtube/libre/falta/"; 

for (int i = 0; i < str.size(); i++) {
    if (str[i] == '/') {
        str[i] = '\\';
    }
}

std::cout << str;

结果:

点:youtube \ resources \音响\ \‘\ \缺失