Home  >  Article  >  Backend Development  >  How to Determine if a String Ends with Another String in C ?

How to Determine if a String Ends with Another String in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 05:31:30464browse

How to Determine if a String Ends with Another String in C  ?

Determining String Suffixes in C

In C , the task of ascertaining whether one string terminates with another is fundamental. To address this, let's delve into a pragmatic solution.

The std::string library furnishes the compare function, which facilitates comparing the last n characters of the full string with the ending string. This is made possible by specifying the offset from the end of the full string and the length of the ending string to compare.

Here's an implementation that embodies this approach:

<code class="cpp">#include <iostream>
#include <string>

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;
    }
}

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

Through the utility function hasEnding, we can ascertain if a given string terminates with another specific string. This functionality is particularly valuable in text processing, string manipulation, and a myriad of other applications.

The above is the detailed content of How to Determine if a String Ends with Another String in C ?. 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