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 관련글 쓰기

|  1  | ...  82  |  83  |  84  |  85  |  86  |  87  |  88  |  89  |  90  | ...  94  |