이 블로그는 http://blog.greenmaru.com으로 이동 하였습니다.
2010년 12월 이후 업데이트는 새로운 블로그를 통해서만 이루어 집니다. 현재 보고 계신 페이지는 2011년 12월에 없어질 예정 이므로, 필요하신 분께서는 새로운 블로그로 링크를 변경해 주시기 바랍니다.
번거롭게 해 드려 죄송합니다.
<greenb>

std::string의 ReplaceAll 함수

요즘은 CString을 ATL에서 사용가능하게 되면서 std::string을 사용할 일이 줄어들긴 했지만, 여전히 유용한 클래스임에는 틀림없다. (특히나 windows개발이 아니라면)

여튼. std::string에서 아쉬운 부분중에 하나인 ReplaceAll 함수를 간단히 구현해 보자.
(물론 iterator등을 이용하는게 정석 이겠지만, 귀찮으니까 -_-)

  1. #include <string>   
  2.   
  3. typedef std::basic_string<TCHAR> _tstring;   
  4.   
  5. _tstring string_replace_all(    
  6.             const _tstring& source,    
  7.             const _tstring& pattern,    
  8.             const _tstring& replace )   
  9. {   
  10.     _tstring result = source;   
  11.     _tstring::size_type pos = 0;   
  12.     _tstring::size_type offset = 0;   
  13.     _tstring::size_type pattern_len = pattern.size();   
  14.     _tstring::size_type replace_len = replace.size();   
  15.   
  16.     while ( ( pos = result.find( pattern, offset ) ) != _tstring::npos )   
  17.     {   
  18.         result.replace( result.begin() + pos,    
  19.                     result.begin() + pos + pattern_len,    
  20.                     replace );   
  21.         offset = pos + replace_len;   
  22.     }   
  23.     return result;   
  24. }  
저작자 표시 비영리 변경 금지
Tag // ,

Trackback Address >> http://greenmaru.com/trackback/9 관련글 쓰기

Comment List

  1. BlogIcon 고명진 2012/01/11 05:09 address / modify or delete / reply

    좋은 기사 감사합니다

  2. BlogIcon 김용대 2012/01/13 16:33 address / modify or delete / reply

    티끌모아 태산

|  1  | ...  92  |  93  |  94  |  95  |  96  |  97  |  98  |  99  |  100  | ...  104  |