How can I replace all occurrences of a character with another character in std string?

Discussion in 'C++' started by herman, Aug 30, 2007.

  1. herman

    herman Guest

    How can I replace all occurrences of a character with another
    character in std string?

    For example, I want to replace '/' with '+' in my std::string

    I have looked at the replace() method in the string class, it does not
    replace all occurrences of a character with another character.

    http://www.cppreference.com/cppstring/index.html

    Thank you
     
    herman, Aug 30, 2007
    #1
    1. Advertisements

  2. herman

    Ian Collins Guest

    You either have to roll your own, or look at a regular expression
    library like boost.regexp:

    http://www.boost.org/libs/regex/doc/introduction.html
     
    Ian Collins, Aug 30, 2007
    #2
    1. Advertisements

  3. Try using std::for_each with a functor. For example

    struct testfunctor
    {
    void operator()(char& c) { if(c == '/') c = '+'; }
    };
    ....
    std::string str("This is a test - /////////\n");
    std::cout << str;
    std::for_each( str.begin(), str.end(), testfunctor() );
    std::cout << str;
     
    Matthew Crisanti, Aug 30, 2007
    #3
  4. herman

    dilipk3 Guest

    var str;
    str.replace(///g,'+');

    /g is for universal char i.e all char in string.
     
    dilipk3, Aug 30, 2007
    #4
  5. herman

    BobR Guest

    // #include <algorithm>
    std::string rep( "?Hello?, ?World?" );
    std::replace( rep.begin(), rep.end(), '?', '+' );
    cout<<"replace ="<<rep<<std::endl;
    // out: replace =+Hello+, +World+
     
    BobR, Aug 30, 2007
    #5
  6. The other people in this group use the C++ language, what do you use?
     
    =?ISO-8859-1?Q?Erik_Wikstr=F6m?=, Aug 30, 2007
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.