0

I have trouble figuring out how to sort a String that has a Number in it.

The String im sending looks like 112:AAAA and 111:EEEE, how would I sort it so that the 111 will be the first in an array but (and here is what I cant figure out) the sorted array should contain the letters again so it would be a String Array that is sorted by the numbers and look like 111:EEEE, 112:AAAA.

I wanted to use what I have seen on C#, having a key and value, but that does not seem to exist in arduino code. So I improvised by writing everything in 1 char array.

edit: I see I'm mixing up char array and string, im very flexible and its no trouble to change to 1 or the other, currently I use char arrays.

I guess it would also be enough to just sort the strings, but i cant find a function for that also.

  • Are the numbers always 3-digit long? If so, you can just lexicographically sort the strings. – Edgar Bonet Sep 23 at 12:22
  • They can be 2-3 digit long – MrAeRoZz Sep 23 at 12:24
1

As Michel Keijzers points out, qsort is the standard sorting function from the libc. Now, since your numbers can start with either two or three digits, you can not sort them lexicographically, because if you did so 111 would sort before 82. Instead I suggest to:

  • parse the start of the strings as integers
  • compare the integers
  • if the integers are equal, then sort the strings lexicographically.

The simplest way to parse the strings into integers is atoi(). Unlike functions like strtol(), atoi() does no error checking, but it is good enough if you know for sure that the strings have the right format.

Here is the comparison function:

int compare(const void *a, const void *b)
{
    // Get the strings.
    const char *sa = *(const char * const *) a;
    const char *sb = *(const char * const *) b;

    // First, compare the numeric prefixes.
    int ia = atoi(sa);
    int ib = atoi(sb);
    if (ia < ib) return -1;
    if (ia > ib) return +1;

    // If equal, compare the strings lexicographically.
    return strcmp(sa, sb);
}

And here is an example on how to use it:

#define STR_COUNT 3
const char *strings[STR_COUNT] = { "112:AAAA", "82:FFFF", "111:EEEE" };
qsort(strings, STR_COUNT, sizeof strings[0], compare);

Now the array of strings is sorted as ("82:FFFF", "111:EEEE", "112:AAAA").

0

You can use the qsort function (see c-library-function-to-do-sort).

With the user definable comp function you can get the first two or three characters, convert it to in integer and compare it against the converted integer from another element.

I would not advise to use strings, because of the limited SRAM storage of an Arduino, you might run out of memory too fast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.