볼랜드 C++빌더/카일릭스의 VCL/CLX에는 다음과 같이 StringReplace() 함수가 있어서
문자열 치환을 손쉽게 할 수가 있습니다.
extern PACKAGE AnsiString __fastcall StringReplace(const AnsiString S, const AnsiString OldPattern, const AnsiString NewPattern, TReplaceFlags Flags);
STL에서 이와 같은 기능을 하는 함수 string_replace()를 구현해 보았습니다.
VCL/CLX의 StringReplace 소스 코드(파스칼)를 바탕으로 string용으로 수정했습니다.
멤버 함수인 find()와 substr()을 사용했습니다.
string string_replace(const string& s, const string& old_pattern,
const string& new_pattern, bool replace_all, bool ignore_case)
{
string search_str = s, patt = old_pattern, new_str = s, result = "";
if (ignore_case) {
locale loc;
const ctype<char>& ct = use_facet<ctype<char> >(loc); // Get a ctype facet
ct.toupper(search_str.begin(), search_str.end());
ct.toupper(patt.begin(), patt.end());
} // 이 부분이 이해가 안 되시는 분은 다음 팁을 참고하세요.
//
http://www.borlandforum.com/impboard/impboard.dll?action=read&db=cpp_tip&no=16
size_t offset, patt_len = patt.length();
while (search_str != "") {
if ((offset = search_str.find(patt)) != string::npos) {
result += new_str.substr(0, offset) + new_pattern;
new_str =
new_str.substr(offset + patt_len, new_str.length());
if (replace_all)
search_str =
search_str.substr(offset + patt_len, search_str.length());
else {
result += new_str;
break;
}
} else {
result += new_str;
break;
}
}
return result;
}
다음은 string_replace()를 사용하는 예제입니다.
파일에서 한 라인씩 읽어서 특정 문자열을 검색해서 다른 문자열로 치환합니다.
//---------------------------------------------------------------------------
#include <cstdlib>
#include <iostream>
#include <fstream>
#pragma hdrstop
#include <string>
//---------------------------------------------------------------------------
#pragma argsused
using namespace std;
string string_replace(const string& s, const string& old_pattern,
const string& new_pattern, bool replace_all = true, bool ignore_case = false);
int main(int argc, char* argv[])
{
if (argc < 4) {
cerr << "Usage: " << argv[0]
<< " input_file output_file old_pattern new_pattern\n";
exit(0);
}
ifstream fin(argv[1]);
ofstream fout(argv[2]);
string old_pattern(argv[3]);
string new_pattern(argv[4]);
string sLine, sReplacedLine;
while(getline(fin, sLine)) {
sReplacedLine = string_replace(sLine, old_pattern, new_pattern);
fout << sReplacedLine << endl;
}
return 0;
}