std::string의 개행 문자들을 다 지우는 방법

조회수 11248회

string의 개행 문자들(\n, \r, \t 포함)을 다 지우고 싶어요. 지금 밑에 방법 쓰고 있는데 더 좋은 방법 있을까요? 아, 그리고 앞에 있는 개행 문자를 지우는 방법도 알려주세요

소스코드

std::string s;
s.erase(s.find_last_not_of(" \n\r\t")+1);

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    경우에 따라 다르긴 한데 저는 3가지 방법 써요

    #include <algorithm> 
    #include <functional> 
    #include <cctype>
    #include <locale>
    
    //앞에 있는 개행 문자 제거
    static inline std::string &ltrim(std::string &s) {
            s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
            return s;
    }
    
    //뒤에 있는 개행 문자 제거
    static inline std::string &rtrim(std::string &s) {
            s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
            return s;
    }
    
    //양쪽 끝의 개행 문자 제거
    static inline std::string &trim(std::string &s) {
            return ltrim(rtrim(s));
    }
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)