Thread: Help with String functions

  1. #1
    Registered User
    Join Date
    Apr 2007

    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:

    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
    The second parameter to erase should be the number of characters to erase, right?

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

    #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, 06:16 AM
  5. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM