开发者

Problem comparing strings containing numbers

开发者 https://www.devze.com 2023-01-12 09:04 出处:网络
hello i got a problem with comparing two char* variables that contains numbers for example char1 = \"999999\" and char2=\"11111111\"

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).


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.


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
}


If the strings have no leading/trailing garbage, use this algorithm:

  • Compare the lengths of the two strings using strlen(). The longer one is always the biggest.
  • If the length are equal, use strcmp().


You can convert a string to a 64-bit integer using _atoi64. Then, you can just compare them directly as you'd expect. Depending on your compiler, _atoi64 might be called something different.


shortest way should be:

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


It is ordered literally, which means that something starting on 9 will always be greater than something starting on 1. If you need to do an integer comparison, you'll have to use atoi.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号