mercredi 25 septembre 2019

Extracting a substring to the last-nth delimiter C++

I am trying in C++ to find

  1. the most performant
  2. the most elegant

code that takes a string and an integer and for a given delimiter, let's say ".", results to the nth from the last substring.

Example Input:

string "a.b.c.d.e" and delimFromEndLevel = 1 => string "a.b.c.d"

string "a.b.c.d.e" and delimFromEndLevel = 2 => string "a.b.c"

etc.

Starting point is the following code:

void elaborateParent( const std::string& input, unsigned int levels )
{
    std::size_t cutOffIndex = std::string::npos;
    while (levels > 0)
    {
        cutOffIndex = input.rfind('.', cutOffIndex);
        if (cutOffIndex == std::string::npos)
            std::cout << "Not enough levels to go up!" << std::endl; 
        levels--;
        if (levels>0)
        {
            if (cutOffIndex>0)
                cutOffIndex--;
            else
                std::cout << "Not enough levels to go up!" << std::endl;
        }
    }
    std::string result = input.substr(0, cutOffIndex);
    std::cout << "Elaboration parent result: '" << result << "'" << std::endl;
}

Aucun commentaire:

Enregistrer un commentaire