The following code implements a getSubstrSmallestNumber()
function which uses the strtok()
function which changes the input buffer. If you don't want that you can first copy the string. The good point about changing the input buffer is that no memory allocation is needed for the found sub string. The strtok()
writes a null terminator '\0'
where the specified delimiter is found if it's called.
The getSubstrSmallestNumber()
function can called with specific delimiters, here '@'
and ' '
. Each number will be converted to double with strtod()
and checked if it smaller than before. If it's smaller the corresponding token will be saved. After the while loop finished (if strtok()
found no more tokens) the saved token (smallest double) will be returned.
Note that the code does no error checking this should be considered to be implemented as well.
Full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <float.h>
char* getSubstrSmallestNumber(char* input, char* numberDelimiter, char* strDelimiter)
{
char* tokenStr;
double minNumber = DBL_MAX;
char* minToken = NULL;
for (tokenStr = strtok(input, numberDelimiter);
tokenStr != NULL;
tokenStr = strtok(NULL, numberDelimiter))
{
char* numberStr = strtok(NULL, strDelimiter);
double number = strtod(numberStr, NULL);
if (number < minNumber)
{
minNumber = number;
minToken = tokenStr;
}
}
return minToken;
}
int main()
{
char input[] = "ash@19.96 ram@12.3 driver@10.2";
printf("<%s>\n", getSubstrSmallestNumber(input, "@", " "));
return 0;
}
Output:
<driver>
I put '<'
and '>'
around the string in the printf()
call to show that the returned string by getSubstrSmallestNumber()
is really just driver
and nothing more like a space for example.