Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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;
}

The string::find method will return the first occurrence of a character in the string, whereas you want the last occurrence.

You're more likely after the string::find_last_of method:
refer: http://www.cplusplus.com/reference/string/string/find_last_of/

Here is a simple C implementation:

void GetFileExt(char* ext, char* filename)
{
  int size = strlen(filename);
  char* p = filename + size;
  for(int i=size; i >= 0; i--)
  {
    if( *(--p) == '.' )
    {
      strcpy(ext, p+1);
      break;
    }
  }
}


int main()
{
    char ext[10];
    char filename[] = "nome_del_file.txt";

    GetFileExt(ext, filename);

}

You can use this as starting point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top