Search code examples
c++loopscode-duplication

Preventing code duplication in and outside of a loop


I have a problem rewriting a loop:

else if( "d" == option || "debug" == option )
{
    debug(debug::always) << "commandline::set_internal_option::setting debug options: "
                         << value << ".\n";
    string::size_type index = 0;
    do
    {
        const string::size_type previous_index = index+1;
        index=value.find( ',', index );
        const string item = value.substr(previous_index, index);
        debug::type item_enum;
        if( !map_value(lib::debug_map, item, item_enum) )
            throw lib::commandline_error( "Unknown debug type: " + item, argument_number );

        debug(debug::always) << "commandline::set_internal_option::enabling " << item
                             << " debug output.\n";
        debug(debug::always) << "\n-->s_level=" << debug::s_level << "\n";
        debug::s_level = static_cast<debug::type>(debug::s_level ^ item_enum);
        debug(debug::always) << "\n-->s_level=" << debug::s_level << "\n";
    } while( index != string::npos );
}

value is something like string("commandline,parser") and the problem is that in the first run, I need substr(previous_index, index), but in every subsequent iteration I need substr(previous_index+1, index) to skip over the comma. Is there some easy way I'm overlooking or will I have to repeat the call to find outside the loop for the initial iteration?


Solution

  • Why not update previous_index after taking the substr?

    string::size_type index = 0;
    string::size_type previous_index = 0;
    do {
      index=value.find( ',', previous_index );
      const string item = value.substr(previous_index, index);
      previous_index = index+1;
    } while( index != string::npos );
    

    Unchecked, but this should do the trick (with only one more word of memory).