Home  >  Article  >  Backend Development  >  How to Check if a C String Ends with a Specific String?

How to Check if a C String Ends with a Specific String?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 18:53:30576browse

How to Check if a C   String Ends with a Specific String?

Finding String Endings with C

Determining whether a string concludes with another sequence of characters is a common task in programming. In C , this functionality can be easily achieved using the std::string::compare method.

Solution:

To verify if the ending string exists at the end of the full string, we need to compare the last n characters of the fullString against the ending string. Here's a function that performs this task:

<code class="cpp">bool hasEnding(const std::string& fullString, const std::string& ending) {
    if (fullString.length() >= ending.length()) {
        return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending));
    } else {
        return false;
    }
}</code>

Explanation:

  • Check if the fullString is long enough to contain the ending.
  • If so, compare the last n characters of the fullString (where n is the length of the ending) with the ending string using compare.
  • If the comparison returns 0, the strings are identical, and the function returns true. Otherwise, it returns false.

Example Usage:

In the provided main function, we test out the hasEnding function with various strings and an ending string:

<code class="cpp">int main() {
    // Test strings
    std::string test1 = "binary";
    std::string test2 = "unary";
    std::string test3 = "tertiary";
    std::string test4 = "ry";

    // Ending string
    std::string ending = "nary";

    // Print results
    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;
}</code>

Output:

true
false
false
true

The above is the detailed content of How to Check if a C String Ends with a Specific String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn