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:
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!