std::string이 특정 문자로 끝나는지 아닌지 판단하는 함수
조회수 2781회
1 답변
-
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; }
댓글 입력