Help with String functions

This is a discussion on Help with String functions within the C++ Programming forums, part of the General Programming Boards category; I am having trouble with finding and erasing part of a string. For example, the string "pork and beans". We ...

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    17

    Question Help with String functions

    I am having trouble with finding and erasing part of a string. For example, the string "pork and beans". We had to find the first occurrence of "and" and place "not" after the "and" to make it "pork and not beans"

    Then we are supposed to erase the "not".


    all remove() to remove " not" from the string str. The function remove() will receive str as a reference parameter. After changing str, remove() will print the changed string.

    So far I've come up with this:

    Code:
    void remove (string &str)
    {
         string::size_type pos;
        
        pos = str.find ("not", 0);
        str.erase (pos, str.length());
        
        cout << str << endl << endl;
     }
    The second parameter in the erase function is way off, I know. I was just trying anything. I'd appreciate anyones helpn

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,319
    The second parameter to erase should be the number of characters to erase, right?

  3. #3
    Registered User
    Join Date
    May 2007
    Posts
    88
    This is a little hacky, but you get the idea...

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
    	string::size_type pos;
    	string str("pork and beans");
    	string str_to_find("and");
    	pos = str.find (str_to_find, 0);
    	str.insert (pos + str_to_find.size(), " not");
    	cout <<str <<endl;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  2. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  3. RicBot
    By John_ in forum C++ Programming
    Replies: 8
    Last Post: 06-13-2006, 06:52 PM
  4. Badly designed n string functions?
    By anonytmouse in forum C Programming
    Replies: 3
    Last Post: 11-01-2003, 05:16 AM
  5. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 10:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21