I'm trying to extract the file extension part in a string value.
For example, assuming the string value is "file.cpp", I need to extract the "cpp" or ".cpp" part.
I've tried using strtok() but it doesn't return what I am looking for.
Use find_last_of and substr for that task:
std::string filename = "file.cpp";
std::string extension = "";
// find the last occurrence of '.'
size_t pos = filename.find_last_of(".");
// make sure the poisition is valid
if (pos != string::npos)
extension = filename.substr(pos+1);
else
std::cout << "Coud not find . in the string\n";
This should give you cpp as an answer.
This will work, but you'll have to be sure to give it a valid string with a dot in it.
#include <iostream> // std::cout
#include <string> // std::string
std::string GetExtension (const std::string& str)
{
unsigned found = str.find_last_of(".");
return str.substr( found + 1 );
}
int main ()
{
std::string str1( "filename.cpp" );
std::string str2( "file.name.something.cpp" );
std::cout << GetExtension( str1 ) << "\n";
std::cout << GetExtension( str2 ) << "\n";
return 0;
}
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