如何用另一个字符串替换字符串?

时间:2015-01-05 11:40:50

标签: c++ replace

我已经在这个问题上坐了很长时间,但我无法弄清楚该怎么做。

我正在尝试编写一个程序,它读取文本文件,搜索并替换字符串并以新名称保存文件。根据您输入的最小值和最大值以及墨迹,可以创建多个文件。

除了替换字符串(函数replaceVariable)外,一切都有效。

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>
    #include <algorithm>
    #include <conio.h> 
    using namespace std;



    string replaceVariable(string text1, string oldVariable, long double wert){
       cout<< "replace-function open............."<<endl;
       size_t foundAt = text1.find(oldVariable); //find position of old variable
       cout<<"position old variable: "<<foundAt<<endl;

       string newText = to_string(wert); //convert long double 'wert' to string
       cout<<"new variable: "<<newText<<endl;
       size_t lengthNewText = newText.length(); //find length of new string

       string text2= text1.replace(foundAt, lengthNewText, newText); //replace with new string    with length 'lengthNewText' starting at position 'foundAt' 

       return text2;
   }




void writeFile ( string text, string filename ){
    ofstream myfile;
    myfile.open ( filename.c_str() );
    myfile << text;
    cout<<"file written.............."<<endl;
    myfile.close();
  }


template <typename T>
std::string to_string(T const& value) {
    stringstream sstr;
    sstr << value;
    return sstr.str();
}



int main(){

    ifstream inFile;
    inFile.open("C:\\Users\\User\\Desktop\\Test\\testing.txt");//open the input file

    if (inFile.is_open()){
        cout<< "file open"<<endl<<endl;
        stringstream strStream;
        strStream << inFile.rdbuf();
        string str = strStream.str();

        cout << "---------------------------------------------------------------"<<endl;
        cout<< str << endl;
        cout << "---------------------------------------------------------------"<<endl<<endl;
        string line;
        string name;


        long double minWert = 0;
        long double maxWert = 0;
        long double inkWert = 0;



        cout << "Enter minimum value:" << endl;
        cin >> minWert;
        cout << "Enter maximum value:" << endl;
        cin >> maxWert;
        cout << "Enter inkrement:" << endl;
        cin >> inkWert;

        int numFiles = (maxWert-minWert)/inkWert + 1; //calculation number of files needed
        cout << "minimum value: " << minWert << endl;
        cout << "maximum value: " << maxWert << endl;
        cout << "inkrement: " << inkWert << endl;
        cout << "number of files: " << numFiles << endl<<endl<<endl;

        string oldVariable = "xyz     "; //string to be replaced, xyz followed by 5 spaces

        for( int fileNum = 1; fileNum <= numFiles; ++fileNum )  {
            cout<< "loop number: "<< fileNum<<endl; 
            string output = str;

            replaceVariable(output, oldVariable, minWert);

            cout << "---------------------------------------------------------------"<<endl;
            cout << output << endl;
            cout << "---------------------------------------------------------------"<<endl<<endl;

            string text = output;

            name = "C:\\Users\\User\\Desktop\\Test\\comp";
            name += to_string( fileNum );
            name += ".bdf";
            writeFile( text, name );

            cout<<minWert<<endl;

            minWert = minWert+inkWert;

            cout <<"new Minimalwert: "<< minWert<<endl<<endl;
        }
        inFile.close();
    }   else{cout << "Unable to open file";}

 getch();
return 0;
}

我已经搜索了很多网站并搜索了每个可以想象的组合。 你有什么想法可能会有所帮助吗?

2 个答案:

答案 0 :(得分:0)

如果您的功能 'replaceVariable' 正确,那么这可能就是问题,

string output = str;
/*function replaceVariable is returning replaced string but you didn't receive
at the calling place and assign back to output(which you are writing in output file)*/
replaceVariable(output, oldVariable, minWert); 

所以替换为,

string output = replaceVariable(str, oldVariable, minWert);

答案 1 :(得分:0)

您的代码中需要注意几点。

首先,如果找不到模式字符串,string::find可能会返回npos,您应该检查它。

其次,string::replace在原始字符串上执行 inplace 替换,为了获得更好的性能,您可以通过引用传递text1参数。

第三,replaceVariable只替换第一次出现的变量,这真的是你想要的吗?

这是我在字符串中替换模式的版本:

// replaces at most `limit` occurrences of pattern `p` in text `s` with string `repl`.
// if `limit` <= 0, replace all occurrences.
// returns number of replacement that actually took place.
int replace(std::string &s, const std::string &p, const std::string &repl, int limit=0) {
  int nrepl = 0;
  size_t pos = 0,
         plen = p.length(),
         rlen = repl.length(),
         npos = std::string::npos;

  while ((pos = s.find(p, pos)) != npos) {
    s.replace(pos, plen, repl);
    pos += rlen;
    ++nrepl;
    if (limit > 0 && nrepl >= limit) break;
  }

  return nrepl;
}

希望有所帮助。