The problem of comparing strings containing numbers

Hi, I ran into the problem of comparing two char * variables that contain numbers, for example, char1 = "999999"and char2="11111111" when I use the function strcmp, it will return that the variable char1 is greater than char2 even due to its incorrectness. (I know that I can compare using the atoi function to 9 characters inside a string, but I need to use 10 so that it cuts this opportunity).

+3
source share
6 answers

A slightly more cumbersome way to avoid atoifriends is to prefix the shorter of two lines with zeros. Or, assuming there are no null prefixes, just compare the length first (since shorter lines should have a smaller value) and then do a lexicographic comparison:

int numerical_strcmp(const char* a, const char* b) {
    return (strlen(a) != strlen(b)) ? ((strlen(a) > strlen(b)) ? 1 : -1) : strcmp(a, b);
}

Oh, and that requires strings to contain non-negative numbers.

+4
source

Actually, this is correct. It performs string comparison of string contents, not numerical.

As a quick and dirty hack, if you have already confirmed that the lines contain positive integers, you can do the following:

if (strlen(char2) > strlen(char1)) {
  // char2 > char1
} else if (strlen(char2) == strlen(char1)) {
  cmp = strcmp(char2, char1);
  if (cmp > 0) {
    // char2 > char 1
  } else if (cmp == 0) {
    // char2 == char1
  } else {
    // char2 < char1
  }
} else {
  // char2 < char1
}
+4
source

/ , :

  • strlen(). .
  • , strcmp().
+3

You can convert a string to a 64-bit integer with _atoi64. Then you can simply compare them, as you would expect. Depending on your compiler, there _atoi64may be something else.

+1
source

The shortest path should be:

int mystrcmp(const char *a,const char *b)
{
  return strlen(a)-strlen(b)?strlen(a)-strlen(b):strcmp(a,b);
}
+1
source

This is literally ordered, which means that something starting with 9 will always be more than something starting with 1. If you need to make an integer comparison, you have to use atoi.

0
source

Source: https://habr.com/ru/post/1760976/


All Articles