Thread: String replace

  1. #1
    Registered User
    Join Date
    Mar 2006
    Location
    USA::Colorado
    Posts
    155

    String replace

    Hey everyone,

    I'm trying to find a string within a larger string, then replace it with a value. Here is an example (sudocode)?

    Code:
    string 1 = "this is REPLACE_STRING_HERE!";
    string 2 = "really cool"
    
    string1.replace("REPLACE_STRING_HERE", string2);
    
    cout << string1 << endl; //outputs this is really cool!
    How would I go about doing this?

    Thanks,

    Matt N
    ~guitarist809~

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Use find to find the location of the search string, then use that location plus the search string's size to get the range to replace with the new string.

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    You're quite close already. But replace() wants a position and a length or a pair of iterators to specify the position, so you need to use string::find() to get them.

    Code:
    pos = s.find(search_string);
    if(pos != string::npos) {
      s.replace(pos, search_string.length(), replacement);
    }
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  3. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  4. Errors with program to replace string with another
    By Dan17 in forum C Programming
    Replies: 3
    Last Post: 09-14-2006, 10:15 AM
  5. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM