1234567891011121314151617181920
#include <iostream> #include <string> using namespace std; string getExtension( const string &str ) { size_t p = str.rfind( '.' ); if ( p == string::npos || p == str.size() - 1 ) return ""; return str.substr( p + 1 ); } int main() { string tests[] = { "one.doc", "two.xls", "help", "spam.txt.exe" }; for ( string s : tests ) { string ext = getExtension( s ); cout << s << " : " << ( ext.empty() ? "No extension" : "extension " + ext ) << '\n'; } }
one.doc : extension doc two.xls : extension xls help : No extension spam.txt.exe : extension exe