1

以下に、テキストファイルを読み取り、単語が含まれている場合にのみ別のテキストファイルに行を書き込むコードがあります "unique_chars"。たとえば、その行に他のゴミもあります。フレーズを などの別のもの"column"に置き換えるにはどうすればよいですか?"column""wall"

だから私の行は次のようになります<column name="unique_chars">x22k7c67</column>

#include <iostream>
#include <fstream>

using namespace std;

int main()
{

    ifstream  stream1("source2.txt");
    string line ;
    ofstream stream2("target2.txt");

        while( std::getline( stream1, line ) )
        {
            if(line.find("unique_chars") != string::npos){
             stream2 << line << endl;
                cout << line << endl;
            }

        }


    stream1.close();
    stream2.close();    

    return 0;
}
4

2 に答える 2

2

文字列のすべての出現箇所を置き換えたい場合は、独自のreplaceAll関数を実装できます。

void replaceAll(std::string& str, const std::string& from, const std::string& to) {
    if(from.empty())
        return;
    size_t pos = 0;
    while((pos = str.find(from, pos)) != std::string::npos) {
        str.replace(pos, from.length(), to);
        pos += to.length();
    }
}
于 2012-09-07T22:57:02.287 に答える
1

置換を行うには、std :: stringのメソッド「replace」を使用できます。これには、開始位置と終了位置、および削除するものの代わりとなる文字列/トークンが必要です。

(また、コードに文字列ヘッダーを含めるのを忘れました)

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream  stream1("source2.txt");
    string line;
    ofstream stream2("target2.txt");

    while(getline( stream1, line ))
    {
        if(line.find("unique_chars") != string::npos)
        {
            string token("column ");
            string newToken("wall ");
            int pos = line.find(token);

            line = line.replace(pos, pos + token.length(), newToken);
            stream2 << line << endl;
            cout << line << endl;
        }
    }

    stream1.close();
    stream2.close();    

    system("pause");
    return 0;
}
于 2012-09-07T22:57:17.773 に答える