In C++, extracting file extensions from strings is a common task, especially when handling file input/output. There are several approaches to achieve this, and I will introduce two commonly used methods:
Method 1: Using the Standard Library Function find_last_of
This method leverages the find_last_of function of the std::string class to locate the position of the last dot (".") in the filename, enabling the extraction of the extension.
cpp#include <iostream> #include <string> std::string getExtension(const std::string& filename) { // Locate the position of the last dot size_t lastDot = filename.find_last_of("."); if (lastDot == std::string::npos) { return ""; // No dot found, indicating no extension } return filename.substr(lastDot + 1); } int main() { std::string filename = "example.txt"; std::string extension = getExtension(filename); std::cout << "File extension: " << extension << std::endl; return 0; }
Method 2: Using std::filesystem::path
In C++17 and later versions, std::filesystem provides more robust and intuitive file system handling capabilities. With this library, obtaining file extensions becomes straightforward.
cpp#include <iostream> #include <filesystem> std::string getExtension(const std::string& filename) { std::filesystem::path filePath(filename); return filePath.extension().string(); } int main() { std::string filename = "example.txt"; std::string extension = getExtension(filename); std::cout << "File extension: " << extension << std::endl; return 0; }
The std::filesystem::path::extension() method directly returns the extension including the dot ("."). If you require the extension without the dot character, you can make minor adjustments to the returned string.
Summary
Both methods have distinct advantages and trade-offs. The first method is compatible with earlier C++ versions (not requiring C++17), offering better portability, though it involves more manual handling. The second method provides concise, readable code but necessitates C++17 or later. In practice, select the appropriate method based on your project requirements and compiler support.