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!