How to replace all occurrences of a character in string?

后端 未结 15 1502
别那么骄傲
别那么骄傲 2020-11-22 05:54

What is the effective way to replace all occurrences of a character with another character in std::string?

15条回答
  •  野的像风
    2020-11-22 06:33

    This works! I used something similar to this for a bookstore app, where the inventory was stored in a CSV (like a .dat file). But in the case of a single char, meaning the replacer is only a single char, e.g.'|', it must be in double quotes "|" in order not to throw an invalid conversion const char.

    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
        int count = 0;  // for the number of occurences.
        // final hold variable of corrected word up to the npos=j
        string holdWord = "";
        // a temp var in order to replace 0 to new npos
        string holdTemp = "";
        // a csv for a an entry in a book store
        string holdLetter = "Big Java 7th Ed,Horstman,978-1118431115,99.85";
    
        // j = npos
        for (int j = 0; j < holdLetter.length(); j++) {
    
            if (holdLetter[j] == ',') {
    
                if ( count == 0 ) 
                {           
                    holdWord = holdLetter.replace(j, 1, " | ");      
                }
                else {
    
                    string holdTemp1 = holdLetter.replace(j, 1, " | ");
    
                    // since replacement is three positions in length,
                    // must replace new replacement's 0 to npos-3, with
                    // the 0 to npos - 3 of the old replacement 
                    holdTemp = holdTemp1.replace(0, j-3, holdWord, 0, j-3); 
    
                    holdWord = "";
    
                    holdWord = holdTemp;
    
                }
                holdTemp = "";
                count++;
            }
        } 
        cout << holdWord << endl;
        return 0;
    }
    
    // result:
    Big Java 7th Ed | Horstman | 978-1118431115 | 99.85
    

    Uncustomarily I am using CentOS currently, so my compiler version is below . The C++ version (g++), C++98 default:

    g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)
    Copyright (C) 2015 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    

提交回复
热议问题