Search and Replace

This is a discussion on Search and Replace within the C++ Programming forums, part of the General Programming Boards category; Say I have this string which contains >4000 characters, and I want every occurance of the character "I" to be ...

  1. #1
    Registered User
    Join Date
    Nov 2002
    Posts
    8

    Search and Replace

    Say I have this string which contains >4000 characters, and I want every occurance of the character "I" to be replaced with the character "E", how could I do that ?

    I have searched, and searched again, but couldn't find anything I could use/quite understand.

    I've tried stuff like:
    Code:
    string.replace(string.find("I"), 1, "E");

  2. #2
    Registered User
    Join Date
    Apr 2002
    Posts
    1,571
    You can use the STL's replace_if function. Look it up on google for proper usage or wait 20 minutes and I will get bored and post it.

  3. #3
    Registered User
    Join Date
    Nov 2002
    Posts
    8
    well please do )

  4. #4
    booyakasha
    Join Date
    Nov 2002
    Posts
    208
    try

    for(int i = 0 ; i < string.size() ; i++) if( string[i] == 'I' ) string[i] = 'E'

  5. #5
    Registered User
    Join Date
    Apr 2002
    Posts
    1,571
    I have found that the STL's replace_if is faster than your method. Here is a sample of its usage.

    Code:
    #include <string>
    #include <algorithm>
    #include <iostream>
    
    using namespace std;
    
    // Here is our functor
    class LetterCheck
    {
      private:
    
        char test;
    
      public:
    
        LetterCheck( char _test ) : test(_test) { }
        
        bool operator( )( char _test ) { return( test == _test ); }
    };
    
    int main( void )
    {
      string s = "HELLO WORLD";
      
      cout << s << endl;
    
      replace_if( s.begin(), s.end(), LetterCheck('E'), 'I' );
    
      cout << s << endl;
    
      return 0;
    }
    EDIT: I posted one with a simple standard C style function that checked for a specific letter. Here I replaced the function with a functor and its a little more flexible. Good luck.
    Last edited by MrWizard; 12-26-2002 at 03:29 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. vector search and replace
    By rahulsk1947 in forum C++ Programming
    Replies: 6
    Last Post: 06-04-2009, 10:13 PM
  2. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  3. IDEA: Search And Replace
    By ygfperson in forum Contests Board
    Replies: 1
    Last Post: 08-13-2002, 12:28 AM
  4. open file, search of word, replace word with another
    By Unregistered in forum C++ Programming
    Replies: 0
    Last Post: 06-05-2002, 02:16 PM
  5. Search and replace coding....
    By bishop_74 in forum C++ Programming
    Replies: 5
    Last Post: 12-05-2001, 03:22 PM

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