Extracting a substring to the last-nth delimiter C++ : <p>I am trying in C++ to find </p>

<ol>
<li>the most performant</li>
<li>the most elegant </li>
</ol>

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

<p>Example
Input:</p>

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

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

<p>etc.</p>

<p>Starting point is the following code:</p>

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