Create a compact string representation of a list of integers

This commit is contained in:
Magne Sjaastad
2024-07-04 08:35:45 +02:00
parent ffc1687cc7
commit e63005348c
2 changed files with 51 additions and 0 deletions

View File

@@ -419,3 +419,51 @@ std::set<int> RiaStdStringTools::valuesFromRangeSelection( const std::string& s,
return {}; return {};
} }
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::string RiaStdStringTools::formatRangeSelection( const std::vector<int>& values )
{
if ( values.empty() ) return "";
std::vector<int> sortedNums = values;
std::sort( sortedNums.begin(), sortedNums.end() );
std::ostringstream result;
int start = sortedNums[0];
int end = sortedNums[0];
for ( size_t i = 1; i < sortedNums.size(); ++i )
{
if ( sortedNums[i] == end + 1 )
{
end = sortedNums[i];
}
else
{
if ( start == end )
{
result << start;
}
else
{
result << start << "-" << end;
}
result << ", ";
start = sortedNums[i];
end = sortedNums[i];
}
}
if ( start == end )
{
result << start;
}
else
{
result << start << "-" << end;
}
return result.str();
}

View File

@@ -68,6 +68,9 @@ public:
// The input "-3,5-8,10-", min:1, max:12 will produce {1, 2, 3, 5, 6, 7, 8, 10, 11, 12} // The input "-3,5-8,10-", min:1, max:12 will produce {1, 2, 3, 5, 6, 7, 8, 10, 11, 12}
static std::set<int> valuesFromRangeSelection( const std::string& s, int minimumValue, int maximumValue ); static std::set<int> valuesFromRangeSelection( const std::string& s, int minimumValue, int maximumValue );
// Create a string from a set of values. {1, 2, 3, 5, 6, 7, 8, 10, 11, 12} will be converted to "1, 2, 3, 5-8, 10-12"
static std::string formatRangeSelection( const std::vector<int>& values );
private: private:
template <class Container> template <class Container>
static void splitByDelimiter( const std::string& str, Container& cont, char delimiter = ' ' ); static void splitByDelimiter( const std::string& str, Container& cont, char delimiter = ' ' );