Home >Backend Development >C++ >Here are some potential titles in a question format, based on your provided text: * How to Check if a String Ends with Another String in C ? (Simple and direct) * C : Determining if a String Contai
How to Determine if a String Ends with Another String in C
Determining if one string ends with another is a common programming task. In C , this can be achieved by comparing the last n characters of the strings using the std::string::compare method.
Implementation:
The provided code snippet demonstrates this approach:
<code class="cpp">#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; }</code>
Explanation:
Usage:
In the main function, four test strings are created and a common ending string "nary". The hasEnding function is then called to determine if each test string ends with "nary". The results are printed to the standard output.
You can use this approach to efficiently perform string comparisons and determine if a string contains a specific ending.
The above is the detailed content of Here are some potential titles in a question format, based on your provided text: * How to Check if a String Ends with Another String in C ? (Simple and direct) * C : Determining if a String Contai. For more information, please follow other related articles on the PHP Chinese website!