Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if string ends with another string in C++

How can I find out if a string ends with another string in C++?

like image 451
sofr Avatar asked May 17 '09 08:05

sofr


People also ask

How do you check if a string ends with another string?

The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.

How do you check if a string contains another string in C?

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.

How do you find the end of a 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.

How do you check if a string ends with a number?

Using Character.isDigit(char) method to check if the first character of the string is a digit or not.


2 Answers

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; } 
like image 72
kdt Avatar answered Oct 01 '22 03:10

kdt


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()); } 
like image 32
Joseph Avatar answered Oct 01 '22 04:10

Joseph