matching substring to a list of strings faster

Viewed 60

I've seen a common string parsing scenario in my org and was wondering if there's a better way to achieve it, it goes something like this -

I've got an input string that represents a filename+ext eg. abc.txt, abc.2.out, abc.txt.temp, etc) and I've to extract the filename from it.

I also have list of all valid extensions (like .out, .exe, .txt.temp, .txt) with me.

I sort this list in descending order by string::size() such that bigger extensions are matched first and it doesn't end up eager to match similar shorter extensions.

Please note that having a . doesn't mean it's an extension as filenames can also consist of many of these for our case. At the end of processing, I just want a separate name and extension.

Its currently implemented by iterating over the extension list and checking input_string.ends_with(ext) and then erasing the extension to return the actual filename. Is there any better way to do this since that list keeps on growing...??

Extracted code -

vector<string> extensions {"txt","out", "exe", "txt.temp"....};
// sort them by size in desc order
sort(extensions.begin(), extensions.end(), [](auto e1, auto e2) { return e1.size() > e2.size(); });
string filename = getInput();  // hello_world.txt.temp

for(const auto& ext: extensions) {
    if(filename.ends_with(ext)) { // found }
}
0 Answers
Related