Turbo-C
C++Builder  |  Delphi  |  FireMonkey  |  C/C++  |  Free Pascal  |  Firebird
볼랜드포럼 BorlandForum
 경고! 게시물 작성자의 사전 허락없는 메일주소 추출행위 절대 금지
터보-C 포럼
Q & A
FAQ
팁&트릭
강좌/문서
자료실
Lua 게시판
볼랜드포럼 홈
헤드라인 뉴스
IT 뉴스
공지사항
자유게시판
해피 브레이크
공동 프로젝트
구인/구직
회원 장터
건의사항
운영진 게시판
회원 메뉴
북마크
볼랜드포럼 광고 모집

C/C++ 팁&트릭
[7] [STL]AnsiString의 StringReplace와 유사한, string_replace()의 구현
김백일 [cedar] 5267 읽음    2002-05-09 06:11
볼랜드 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;
}

+ -

관련 글 리스트
7 [STL]AnsiString의 StringReplace와 유사한, string_replace()의 구현 김백일 5267 2002/05/09
Google
Copyright © 1999-2015, borlandforum.com. All right reserved.