How can I find out if a string ends with another string in C++?
The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.
The function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string. In other words, whether a string is a substring of another string.
To check the end of a string, use the endsWith() method. Let's say the following is our string. String str = "demo"; Now, check for the substring “mo” using the endsWith() method in an if-else condition.
Using Character.isDigit(char) method to check if the first character of the string is a digit or not.
Simply compare the last n characters using std::string::compare
:
#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; }
Use this function:
inline bool ends_with(std::string const & value, std::string const & ending) { if (ending.size() > value.size()) return false; return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With