살아가는 이야기

C++에서 Python의 strip 유사 함수 구현하기 본문

컴퓨터, 풀어그림

C++에서 Python의 strip 유사 함수 구현하기

우균 2016. 10. 25. 09:32

Python의 문자열 함수 중에는 strip()이라는 메소드가 있다. 이 메소드는 문자열의 좌우 공백을 제거한 결과를 반환한다. 좌측만 제거하려면 lstrip(), 우측만 제거하려면 rstrip()을 사용한다. 사용법은 다음과 같다.

>>> s = ' rock, paper, scissors '
>>> s.lstrip()
'rock, paper, scissors '
>>> s.rstrip()
' rock, paper, scissors'
>>> s.strip()
'rock, paper, scissors'
>>> s
' rock, paper, scissors '

그런데 이와 유사한 함수를 C++에서 사용하고 싶으면 어떻게 할까? Boost 라이브러리에 유사 함수가 있다.

#include <boost/algorithm/string.hpp>

std::string str(" rock, paper, scissors ");
boost::trim_left(str);
boost::trim_right(str);
boost::trim(str);

이 함수들은 해당 문자열을 직접 바꾸는 함수들이다.


Boost 라이브러리가 없다면, 다음과 같이 구현할 수 있다.

#include <string>
#include <algorithm>
#include <cctype>

static inline void ltrim(string &s) {
    s.erase(s.begin(), find_if(s.begin(), s.end(),
            not1(ptr_fun(isspace))));
}

static inline void rtrim(string &s) {
    s.erase(find_if(s.rbegin(), s.rend(),
            not1(std::ptr_funstd::isspace))).base(), s.end());
}

static inline void trim(std::string &s) {
    ltrim(s);
    rtrim(s);
}




Comments