Reputation: 619
I have a simple C code which needs to compare to numbers. But the numbers are array of characters. which method will be fast to compare these numbers 1) Compare to array of numbers using strcmp function. 2) convert each number string back to number using atoi function and then compare both.
In last, I have to put back these numbers into text file.
int main(int argc, char* argv[]){
char nubmer1[] = "12823423";
char number2[] = "12453453";
//compare logic here. and need help with this.
//print to .txt file logic here. i have this with me.
}
Upvotes: 0
Views: 351
Reputation: 6684
First you need to have a uniform,pre-defined format of number representation. This simplifies the following logic.
You can check if two numbers are equal or not, using strncmp() == 0 is advisable.(Avoid strcmp for security reasons, though).
If you want to check if a number is greater or less than another number: 1. First check if both of them are positive or both are negative . 2. If condition 1 is true, check string length. The one that has greater length is obviously greater. Else check whichever has a -ve sign, is smaller than the positive or unsigned number. 3. If both strings are of same length, then compare byte by byte and find out which one is greater or lesser. NOTE when comparing negative number and positive numbers, the logic is different. -2<-1, but +2>+1
You can optimize further in the above given logic as much as you want based on your design.
You do not need to convert them to integers for operations like >,<,= and stuff, unless you are dealing with really large numbers and have to do some arithmetic calculations.
Upvotes: 0
Reputation: 646
I think you can do a experiment on this, write a test program, nice thing for your.
Upvotes: -1
Reputation: 81
But it wont be correct. What if you have leading 0's? strcmp will not match it, but converting to numbers will.
You should think whether that matters before deciding. If the numbers are always guaranteed to be pure integers, stripping leading zeros and then strcmp would work.
Upvotes: 1
Reputation: 3125
strcmp will check if both numbers are equal or not. it will not check for greater than or less than in case if both numbers are not of equal lenght. So first check using strlen, if their lengths are equal then check using strcmp.
Upvotes: 0
Reputation: 2039
If by "compare" you only need to know if they are not equal, strcmp is the fastest since converting them to integers will include scanning the strings and doing some multiplications before doing the comparison.
Upvotes: 4