Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem comparing strings containing numbers

hello i got a problem with comparing two char* variables that contains numbers for example char1 = "999999" and char2="11111111" when i am using the strcmp function it will return that char1 variable is greater than char2 even tho its wrong. (i know that i can compare with using the atoi function till 9 chars inside the string but i need to use 10 so it cuts this possibility).

like image 285
Nadav Avatar asked Dec 13 '25 04:12

Nadav


2 Answers

A slightly more cumbersome way, that avoids atoi and friends, is to prefix the shorter of the two strings with zeroes. Or, assuming there are no prefixing zeroes, simply first comparing the length (since shorter strings must have a lower value), then running a lexiographic 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 this requires the strings to contain non-negative numbers.

like image 164
You Avatar answered Dec 14 '25 19:12

You


Actually, it's right. It's doing a string comparison of the contents of the strings, not a numeric one.

As a quick and dirty hack, assuming that you've already validated that the strings contain positive integers, you could 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
}
like image 36
David Knell Avatar answered Dec 14 '25 19:12

David Knell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!