std::string이 특정 문자로 끝나는지 아닌지 판단하는 함수

조회수 2783회

python에서는 string.endwith로 검사할 수 있었는데

C++에도 std::string이 특정 문자로 끝나는지 아닌지 판단하는 함수가 있나요?

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    C++은 문자열 자체를 비교하는 기능은 있지만 "특정 문자열로 끝나는지" 알려주는 함수는 없습니다. 그래서 직접 구현하셔야 합니다.

    #include <iostream>
    
    /*fillString이 ending으로 끝나는지 확인해주는 함수*/
    bool hasEnding (std::string const &fullString, std::string const &ending) {
        if (fullString.length() >= ending.length()) {
            return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending)); //fullString의 길이에서 ending의 길이만큼 뺀 위치부터 같은지 검사
        } else { //fullString의 길이보다 ending의 길이가 긴 경우 -> 항상 거짓
            return false;
        }
    }
    
    int main () {
        std::string test1 = "binary";
        std::string test2 = "unary";
        std::string test3 = "tertiary";
        std::string test4 = "ry";
        std::string ending = "nary";
    
        std::cout << hasEnding (test1, ending) << std::endl;
        std::cout << hasEnding (test2, ending) << std::endl;
        std::cout << hasEnding (test3, ending) << std::endl;
        std::cout << hasEnding (test4, ending) << std::endl;
    
        return 0;
    }
    

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

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

(ಠ_ಠ)
(ಠ‿ಠ)