Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Extract string after dot

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.

like image 986
pogoyogo Avatar asked Feb 03 '26 20:02

pogoyogo


2 Answers

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.

like image 73
maddin45 Avatar answered Feb 05 '26 09:02

maddin45


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;
}
like image 29
ParvusM Avatar answered Feb 05 '26 10:02

ParvusM