C++ : string beginWith and endWith

Summary

C++ string manipulation frequently involves determining if a string starts or ends with a particular substring. To address this common need, two utility functions are presented: `beginWith` and `endWith`. The `beginWith` function efficiently checks for a prefix by comparing the initial segment of the string using `std::string::compare`. Conversely, `endWith` verifies a suffix by comparing the trailing part of the string, incorporating a length check to ensure valid indexing before calling `std::string::compare`. These functions offer practical solutions for common string pattern matching scenarios in C++.

C++ is an very powerful programming language. It is efficient and flexible. When writing C++ programs, we may often need to process strings and often we need to check whether a string begin with some substring or end with some substring. We can use following functions to ahieve these:

    static bool beginWith(const std::string str,const std::string needle){
        return (!str.compare(0,needle.length(),needle));
    }

    static bool endWith(const std::string str,const std::string needle){
        if (str.length() >= needle.length()) {
            return (0 == str.compare (str.length() - needle.length(), needle.length(), needle));
        }
        return false;
    }

C++ BEGINWITH ENDWITH

  RELATED

No related programming articles found. Browse all programming tutorials and articles.

  COMMENT

1
Kaley
May 26, 2018 at 11:45 am
Great article, just what I needed. tottenham tröja