how to do a replace string?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Pleasehelp
    New Member
    • Oct 2007
    • 3

    how to do a replace string?

    Hi,

    lets say if i have a string "mississipp i". is there any method available in c++ that let me say replace all the "s" into maybe "a"? and the result of the query would be "miaaiaaipp i".

    Hope u all understand my above query and would gladly appreciate if anyone could help!
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    You could iterate over the string, checking if the character is 's' and make it 'a' instead. I don't know of any built in C++ string method that will do this character find and replace.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      This is where you use the transform algorithm:
      [code=cpp]
      transform(str.b egin(), str.end(), convertedstr.be gin(), aFunction);
      [/code]

      transform will call the unary function aFunction with each element of str. This function can test for s and change it to a.

      Algorithms are put into the STL to avoid writing billions of member functions on classes like string.

      Comment

      • Pleasehelp
        New Member
        • Oct 2007
        • 3

        #4
        For the transform method, is there any website i can refer to get examples and more on the arguments. i cant seem it find it on the net.
        i am wondering how to input the above method for my case

        Comment

        • Laharl
          Recognized Expert Contributor
          • Sep 2007
          • 849

          #5
          Originally posted by Pleasehelp
          For the transform method, is there any website i can refer to get examples and more on the arguments. i cant seem it find it on the net.
          i am wondering how to input the above method for my case
          http://www.cplusplus.c om/reference/algorithm/transform.html

          The examples are a little farther down from all the complicated stuff.

          Comment

          • Pleasehelp
            New Member
            • Oct 2007
            • 3

            #6
            any idea how i can iterate a string? i am having trouble understanding the transform method. thus decided to go with iterating over the whole string and changing instead. any suggestions?

            Comment

            • sicarie
              Recognized Expert Specialist
              • Nov 2006
              • 4677

              #7
              Did you read through the tutorial above? What part were you confused on? We can help you figure that out.

              But if you're set on iterating through the string, just create a pointer to a char and point it at the location where the string begins.

              Comment

              Working...