programing

문자열이 C++에서 다른 문자열로 끝나는지 확인합니다.

instargram 2023. 4. 17. 21:18
반응형

문자열이 C++에서 다른 문자열로 끝나는지 확인합니다.

C++에서 문자열이 다른 문자열로 끝나는지 확인하려면 어떻게 해야 하나요?

다음 명령을 사용하여 마지막 n개의 문자를 비교합니다.

#include <iostream>

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));
    } else {
        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;
}

다음 기능을 사용합니다.

inline bool ends_with(std::string const & value, std::string const & ending)
{
    if (ending.size() > value.size()) return false;
    return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}

boost::algorithm::ends_with(예: http://www.boost.org/doc/libs/1_34_0/doc/html/boost/algorithm/ends_with.html 참조):

#include <boost/algorithm/string/predicate.hpp>

// works with const char* 
assert(boost::algorithm::ends_with("mystring", "ing"));

// also works with std::string
std::string haystack("mystring");
std::string needle("ing");
assert(boost::algorithm::ends_with(haystack, needle));

std::string haystack2("ng");
assert(! boost::algorithm::ends_with(haystack2, needle));

주의: c++20부터 시작합니다. std::stringc++에 있는 c++30 문자열이 드디어 사용할 수 있게 될 가능성이 있는 것 같습니다.먼 훗날 이 글을 읽지 않으시면 이것들을 사용하실 수 있습니다.startsWith/endsWithC++17:

#if __cplusplus >= 201703L // C++17 and later 
#include <string_view>

static bool endsWith(std::string_view str, std::string_view suffix)
{
    return str.size() >= suffix.size() && 0 == str.compare(str.size()-suffix.size(), suffix.size(), suffix);
}

static bool startsWith(std::string_view str, std::string_view prefix)
{
    return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix);
}
#endif // C++17

오래된 C++를 사용하고 있는 경우는, 다음과 같이 사용할 수 있습니다.

#if __cplusplus < 201703L // pre C++17
#include <string>

static bool endsWith(const std::string& str, const std::string& suffix)
{
    return str.size() >= suffix.size() && 0 == str.compare(str.size()-suffix.size(), suffix.size(), suffix);
}

static bool startsWith(const std::string& str, const std::string& prefix)
{
    return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix);
}

기타 도우미 과부하:

static bool endsWith(const std::string& str, const char* suffix, unsigned suffixLen)
{
    return str.size() >= suffixLen && 0 == str.compare(str.size()-suffixLen, suffixLen, suffix, suffixLen);
}

static bool endsWith(const std::string& str, const char* suffix)
{
    return endsWith(str, suffix, std::string::traits_type::length(suffix));
}

static bool startsWith(const std::string& str, const char* prefix, unsigned prefixLen)
{
    return str.size() >= prefixLen && 0 == str.compare(0, prefixLen, prefix, prefixLen);
}

static bool startsWith(const std::string& str, const char* prefix)
{
    return startsWith(str, prefix, std::string::traits_type::length(prefix));
}
#endif

IMO, c++ 문자열은 분명히 기능하지 않으며 실제 코드에서는 사용되지 않습니다.하지만 적어도 나아질 희망은 있다.

C++에 대한 질문인 것은 알지만, 이것을 하기 위해 좋은 ol'formed C 함수가 필요한 사람이 있다면:


/*  returns 1 iff str ends with suffix  */
int str_ends_with(const char * str, const char * suffix) {

  if( str == NULL || suffix == NULL )
    return 0;

  size_t str_len = strlen(str);
  size_t suffix_len = strlen(suffix);

  if(suffix_len > str_len)
    return 0;

  return 0 == strncmp( str + str_len - suffix_len, suffix, suffix_len );
}

std::mismatch문자열의 끝에서 때 이 할 수 .

const string sNoFruit = "ThisOneEndsOnNothingMuchFruitLike";
const string sOrange = "ThisOneEndsOnOrange";

const string sPattern = "Orange";

assert( mismatch( sPattern.rbegin(), sPattern.rend(), sNoFruit.rbegin() )
          .first != sPattern.rend() );

assert( mismatch( sPattern.rbegin(), sPattern.rend(), sOrange.rbegin() )
          .first == sPattern.rend() );

제 생각에 C++ 솔루션은 다음과 같습니다.

bool endsWith(const std::string& s, const std::string& suffix)
{
    return s.rfind(suffix) == std::abs(s.size()-suffix.size());
}

경고: 일치가 실패하면 스트링 전체가 뒤로 검색된 후 포기됩니다.따라서 많은 사이클이 낭비될 수 있습니다.

let let 렛츠고a처럼 얽혀 있다b당신이 찾는 문자열.a.substr a은 b의 입니다).b)

「」를 사용합니다.std::equal (비밀(이행)<algorithm>)

예:

bool EndsWith(const string& a, const string& b) {
    if (b.size() > a.size()) return false;
    return std::equal(a.begin() + a.size() - b.size(), a.end(), b.begin());
}

std:: equal algorithm에서 합니다.<algorithms>다음 중 하나:

std::string LogExt = ".log";
if (std::equal(LogExt.rbegin(), LogExt.rend(), filename.rbegin())) {
   …
}

C++20부터 도입.

대소문자를 구분하지 않는 버전으로 Joseph의 솔루션을 확장합니다(온라인 데모).

#include <string>
#include <cctype>

static bool EndsWithCaseInsensitive(const std::string& value, const std::string& ending) {
    if (ending.size() > value.size()) {
        return false;
    }
    return std::equal(ending.crbegin(), ending.crend(), value.crbegin(),
        [](const unsigned char a, const unsigned char b) {
            return std::tolower(a) == std::tolower(b);
        }
    );
}

스트링을 사용할 수 있습니다.: scringind

코멘트에 근거한 완전한 예:

bool EndsWith(string &str, string& key)
{
size_t keylen = key.length();
size_t strlen = str.length();

if(keylen =< strlen)
    return string::npos != str.rfind(key,strlen - keylen, keylen);
else return false;
}

위와 똑같이, 여기 내 해결책이 있다.

 template<typename TString>
  inline bool starts_with(const TString& str, const TString& start) {
    if (start.size() > str.size()) return false;
    return str.compare(0, start.size(), start) == 0;
  }
  template<typename TString>
  inline bool ends_with(const TString& str, const TString& end) {
    if (end.size() > str.size()) return false;
    return std::equal(end.rbegin(), end.rend(), str.rbegin());
  }

아래를 사용하여 str에 접미사가 있는지 확인합니다.

/*
Check string is end with extension/suffix
*/
int strEndWith(char* str, const char* suffix)
{
  size_t strLen = strlen(str);
  size_t suffixLen = strlen(suffix);
  if (suffixLen <= strLen) {
    return strncmp(str + strLen - suffixLen, suffix, suffixLen) == 0;
  }
  return 0;
}

라이브러리 기능을 사용하지 않는 원시 솔루션을 게시하는 것이 타당하다고 생각했습니다.

// Checks whether `str' ends with `suffix'
bool endsWith(const std::string& str, const std::string& suffix) {
    if (&suffix == &str) return true; // str and suffix are the same string
    if (suffix.length() > str.length()) return false;
    size_t delta = str.length() - suffix.length();
    for (size_t i = 0; i < suffix.length(); ++i) {
        if (suffix[i] != str[delta + i]) return false;
    }
    return true;
}

" " " 추가std::tolower하게 할 수.

// Checks whether `str' ends with `suffix' ignoring case
bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
    if (&suffix == &str) return true; // str and suffix are the same string
    if (suffix.length() > str.length()) return false;
    size_t delta = str.length() - suffix.length();
    for (size_t i = 0; i < suffix.length(); ++i) {
        if (std::tolower(suffix[i]) != std::tolower(str[delta + i])) return false;
    }
    return true;
}

Grzegorz Bazior 응답에 대해이 실장을 사용했는데 원래 실장에 버그가 있습니다(비교하면 true가 반환됩니다).".so"를 사용합니다.수정된 기능을 제안합니다.

bool endsWith(const string& s, const string& suffix)
{
    return s.size() >= suffix.size() && s.rfind(suffix) == (s.size()-suffix.size());
}

다른 옵션은 regex를 사용하는 것입니다.다음 코드는 대소문자를 구분하지 않는 검색입니다.

bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
  return std::regex_search(str,
     std::regex(std::string(suffix) + "$", std::regex_constants::icase));
}

효율적이지는 않지만 구현은 용이합니다.

유사한 "start With" 문제에 대한 좋은 답변을 찾았습니다.

C++ std: 문자열이 특정 문자열로 시작되는지 확인하고 하위 문자열을 int로 변환하려면 어떻게 해야 합니까?

솔루션을 채택하여 문자열의 마지막 위치만 검색할 수 있습니다.

bool endsWith(const std::string& stack, const std::string& needle) {
    return stack.find(needle, stack.size() - needle.size()) != std::string::npos;
}

이렇게 하면 짧고 빠르게 표준 c++를 사용하여 읽을 수 있습니다.

저처럼 파일 확장자를 확인하기 위해 종료가 필요한 경우std::filesystem라이브러리:

std::filesystem::path("/foo/bar.txt").extension() == ".txt"
bool EndsWith(const std::string& data, const std::string& suffix)
{
    return data.find(suffix, data.size() - suffix.size()) != std::string::npos;
}

테스트

#include <iostream>
int main()
{
   cout << EndsWith(u8"o!hello!1", u8"o!") << endl; 
   cout << EndsWith(u8"o!hello!", u8"o!") << endl; 
   cout << EndsWith(u8"hello!", u8"o!") << endl; 
   cout << EndsWith(u8"o!hello!o!", u8"o!") << endl; 
   return 0;
}

산출량

0 
1 
1 
1 

만약 당신이 나처럼 C++ 순수주의에 관심이 없다면, 여기 오래된 스쿨 하이브리드가 있습니다.문자열이 몇 글자 이상일 경우 장점이 있습니다.대부분의 경우memcmp구현은 가능한 경우 기계어를 비교합니다.

문자 집합을 제어해야 합니다.예를 들어 이 접근 방식을 utf-8 또는 wchar 타입과 함께 사용할 경우 두 개 이상의 문자가 논리적으로 동일한 경우 등 문자 매핑을 지원하지 않기 때문에 몇 가지 단점이 있습니다.

bool starts_with(std::string const & value, std::string const & prefix)
{
    size_t valueSize = value.size();
    size_t prefixSize = prefix.size();

    if (prefixSize > valueSize)
    {
        return false;
    }

    return memcmp(value.data(), prefix.data(), prefixSize) == 0;
}


bool ends_with(std::string const & value, std::string const & suffix)
{
    size_t valueSize = value.size();
    size_t suffixSize = suffix.size();

    if (suffixSize > valueSize)
    {
        return false;
    }

    const char * valuePtr = value.data() + valueSize - suffixSize;

    return memcmp(valuePtr, suffix.data(), suffixSize) == 0;
}

내 의견:

bool endsWith(std::string str, std::string suffix)
{
   return str.find(suffix, str.size() - suffix.size()) != string::npos;
}
bool endswith(const std::string &str, const std::string &suffix)
{
    string::size_type totalSize = str.size();
    string::size_type suffixSize = suffix.size();

    if(totalSize < suffixSize) {
        return false;
    }

    return str.compare(totalSize - suffixSize, suffixSize, suffix) == 0;
}

언급URL : https://stackoverflow.com/questions/874134/find-out-if-string-ends-with-another-string-in-c

반응형