How to check whether a string ends with another string in C++

3 Answers

0 votes
#include <iostream>

using namespace std;
  
bool string_ends_with(const string s, const string match) {
    // int compare(size_t pos, size_t len, const string& str) const;
	if (s.size() >= match.size() && s.compare(s.size() - match.size(), match.size(), match) == 0)
		return true;
	else
		return false;
}
  
int main() {
    string s = "cpp java php python"; 
      
    if (string_ends_with(s, "python"))
        cout << "yes";
    else
        cout << "no";
}
 
 
  
/*
run:
  
yes
  
*/

 



answered Nov 13, 2019 by avibootz
edited Nov 13, 2019 by avibootz
0 votes
#include <iostream>

using namespace std;
  
bool string_ends_with(const string &s, const string &match) {
    if (match.size() > s.size()) return false;

    return equal(match.rbegin(), match.rend(), s.rbegin());
}
  
int main() {
    string s = "cpp java php python"; 
      
    if (string_ends_with(s, "python"))
        cout << "yes";
    else
        cout << "no";
}
 
 
  
/*
run:
  
yes
  
*/

 



answered Nov 13, 2019 by avibootz
0 votes
#include <iostream>
 
using namespace std;
   
bool string_ends_with(const string s, const string match) {
    int s_len = s.length(); 
    int match_len = match.length(); 
 
    if (s_len < match_len) 
       return false; 
   
    return (s.substr(s_len - match_len, match_len).compare(match) == 0); 
}
   
int main() {
    string s = "cpp java php python"; 
       
    if (string_ends_with(s, "python"))
        cout << "yes";
    else
        cout << "no";
}
  
  
   
/*
run:
   
yes
   
*/

 



answered Nov 14, 2019 by avibootz

Related questions

1 answer 169 views
3 answers 245 views
1 answer 162 views
1 answer 140 views
3 answers 177 views
1 answer 135 views
...