taking the last two letters of a string

I would like to make an if-statement. I would like make a if-statement that activates a function that should only be activated if the last two letters of a word equal -er. Is that possible?
Yes.
1
2
3
4
5
6
7
8
#include <string>
#include <algorithm>

bool tail_equals( const std::string& str, const std::string& expected_tail )
{
    return ( expected_tail.size() <= str.size() ) &&
            std::equal( expected_tail.rbegin(), expected_tail.rend(), str.rbegin() ) ;
}
could you maybe write that with, as an example, the word: seguir.
If the string has an ir at the end, cout something.

Thanks!
you can use substring substr()
http://www.cplusplus.com/reference/string/string/substr/

1
2
3
4
5
string f="seguir";
if((f.substr((f.length()-2),2))=="ir")
{
	cout<<"extracted letters from "<<f<<": "<<f.substr((f.length()-2),2)<<endl;
}
Last edited on
> could you maybe write that with, as an example ...

Couldn't you have done it on your own?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <string>
#include <algorithm>
#include <iostream>

bool tail_equals( const std::string& str, const std::string& expected_tail )
{
    return ( expected_tail.size() <= str.size() ) &&
            std::equal( expected_tail.rbegin(), expected_tail.rend(), str.rbegin() ) ;
}

int main()
{
    const std::string word = "seguir" ;
    const std::string tail = "ir" ;
    if( tail_equals( word, tail ) ) std::cout << "something\n" ;
    if( tail_equals( "cout something", "thing"  ) ) std::cout << "thing\n" ;
}
Topic archived. No new replies allowed.