C++,
pasted
on Sep 23:
|
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
const char * DELIMETER = " ";
int main(void)
{
char pszInput[] = "1 2 3 10 11 12 13 19 199 200 201 202 300 305 499";
char * token = strtok(pszInput, DELIMETER);
bool bFirstNumber = true; // for check ',' print
bool bContinue = false; // for check continuous
int nLastNumber = -10; // Should not continue the first input
while( NULL != token )
{
int nCurrentNumber = atoi(token);
if( (nLastNumber + 1) == nCurrentNumber )
{
// continuous number
bContinue = true;
}
else
{
if( bContinue )
{
// print last
printf("-%d", nLastNumber);
bContinue = false;
}
if( bFirstNumber )
{
printf("%d", nCurrentNumber);
bFirstNumber = false;
}
else
printf(",%d", nCurrentNumber);
}
nLastNumber = nCurrentNumber;
token = strtok( NULL, DELIMETER );
}
printf(".");
return 0;
}
|
Output:
|
|
1-3,10-13,19,199-202,300,305,499.
|
|