Confusion with usage of strcmp() for number strings - c

{
char array[2][10]={"3234","5"};
int n=strcmp(array+0,array+1);
printf("%d",n);
}
The following code prints -1, event though 3234>5.
It however prints 1 if the first number is 5234 or 6234 etc.
What is the logic behind the results?(Are only the first digits taken
into account?)
So, is there a way to compare two number strings without comapring
their actual integer values?

What is the logic behind the results?
strcmp compares characters in the strings, using their values as unsigned char. First, it compares the first character of one string with the first character of the other. If they differ, it reports the first string is “lesser than” the second if its character is lesser than the other’s and it reports “greater than” if the first string’s character is greater. If the characters are equal, then strcmp compares the second characters of the strings, then the third, and so on. (If one string is shorter than the other but is identical up to its end, the null character that terminates it will cause it to be lesser than the other string.)
So, is there a way to compare two number strings without comapring their actual integer values?
There is no standard library routine for this. You could write a routine for it.

Related

C strcmp() with one char difference

My question is that how will strcmp() handle the following case:
strcmp("goodpassT", "goodpass");
I read that the comparison continues until a different character is found or null character (\0) is found in any of the strings. In the above case, when it encounters \0 for the second argument, will it just stop comparison, or will it still compare to the T character ? The return value is 1, but I'm not sure about the stopping condition.
The comparison is done using unsigned char. Thus the shorter string is smaller as its terminating 0 is smaller than other unsigned nonzero char in the longer string.
See http://port70.net/~nsz/c/c11/n1570.html#7.24.4p1
The answer for this function strcmp("goodpassT", "goodpass"); will be 1 only.The point upto which lengths of both the string are same will be compared on the basis of their ASCII value.

What is the difference between memcmp, strcmp and strncmp in C?

I wrote this small piece of code in C to test memcmp() strncmp() strcmp() functions in C.
Here is the code that I wrote:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *word1="apple",*word2="atoms";
if (strncmp(word1,word2,5)==0)
printf("strncmp result.\n");
if (memcmp(word1,word2,5)==0)
printf("memcmp result.\n");
if (strcmp(word1,word2)==0)
printf("strcmp result.\n");
}
Can somebody explain me the differences because I am confused with these three functions?
My main problem is that I have a file in which I tokenize its line of it,the problem is that when I tokenize the word "atoms" in the file I have to stop the process of tokenizing.
I first tried strcmp() but unfortunately when it reached to the point where the word "atoms" were placed in the file it didn't stop and it continued,but when I used either the memcmp() or the strncmp() it stopped and I was happy.
But then I thought,what if there will be a case in which there is one string in which the first 5 letters are a,t,o,m,s and these are being followed by other letters.
Unfortunately,my thoughts were right as I tested it using the above code by initializing word1 to "atomsaaaaa" and word2 to atoms and memcmp() and strncmp() in the if statements returned 0.On the other hand strcmp() it didn't. It seems that I must use strcmp().
In short:
strcmp compares null-terminated C strings
strncmp compares at most N characters of null-terminated C strings
memcmp compares binary byte buffers of N bytes
So, if you have these strings:
const char s1[] = "atoms\0\0\0\0"; // extra null bytes at end
const char s2[] = "atoms\0abc"; // embedded null byte
const char s3[] = "atomsaaa";
Then these results hold true:
strcmp(s1, s2) == 0 // strcmp stops at null terminator
strcmp(s1, s3) != 0 // Strings are different
strncmp(s1, s3, 5) == 0 // First 5 characters of strings are the same
memcmp(s1, s3, 5) == 0 // First 5 bytes are the same
strncmp(s1, s2, 8) == 0 // Strings are the same up through the null terminator
memcmp(s1, s2, 8) != 0 // First 8 bytes are different
memcmp compares a number of bytes.
strcmp and the like compare strings.
You kind of cheat in your example because you know that both strings are 5 characters long (plus the null terminator). However, what if you don't know the length of the strings, which is often the case? Well, you use strcmp because it knows how to deal with strings, memcmp does not.
memcmp is all about comparing byte sequences. If you know how long each string is then yeah, you could use memcmp to compare them, but how often is that the case? Rarely. You often need string comparison functions because, well... they know what a string is and how to compare them.
As for any other issues you are experiencing it is unclear from your question and code. Rest assured though that strcmp is better equipped in the general case for string comparisons than memcmp is.
strcmp():
It is used to compare the two string stored in two variable, It takes some time to compare them. And so it slows down the process.
strncmp():
It is very much similar to the previous one, but in this one, it compares the first n number of characters alone. This also slows down the process.
memcmp():
This function is used compare two variables using their memory. It doesn't compare them one by one, It compares four characters at one time. If your program is too concerned about speed, I recommend using memcmp().
To summarize:
strncmp() and strcmp() treat a 0 byte as the end of a string, and don't compare beyond it
to memcmp(), a 0 byte has no special meaning
strncmp and memcmp are same except the fact that former takes care of NULL terminated string.
For strcmp you'll want to be only comparing what you know are going to be strings however sometimes this is not always the case such as reading lines of binary files and there for you would want to use memcmp to compare certain lines of input that contain NUL characters but match and you may want to continue checking further lengths of input.

String Comparison

I am new to C.
I have a code that reads first word from the line, Here is a piece of it:
scanf(Line, "%s", Word);
printf("%s\n", Word);
This code reads and prints the first word in the line. However, I need to compare the first word of the line to another word. Any suggestions?
strcmp(str1,str2)
Compares the C string str1 to the C string str2.
This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
Returns an integral value indicating the relationship between the strings:
A zero value indicates that both strings are equal.
A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2;
A value less than zero indicates the opposite.
Use strcmp(firststring, secondstring) it will return 0, 1, or -1.
If both strings are identical then the strcmp() function will return 0.
If the first character that does not match has a greater value in firststring, it will return 1.
Otherwise, it will return -1.
Take a look at strcmp
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1057537653&id=1043284385
You're looking to split words based on some character. In this case ' '. You should be finding the index of the space and then storing the two words into two new strings.

which method is fast, comparing two number strings or converting them into nunber's and then comparing

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.
}
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.
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.
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.
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.
I think you can do a experiment on this, write a test program, nice thing for your.

convert char array to integer value and add them

How can I extract numbers from a char array, separated with spaces, convert them to integers and sum them? For example:
"34 54 3 23"
I'd start at the beginning of the array, check each character in turn with isdigit() and keep a current value and a current total.
When reaching the terminating NUL char (or last element of the array), the current total is already calculated.
You need to parse the string.
If you know how many integers are in there, you could use just a sscanf.
Otherwise find out where blanks are (with something similar to strtok, for example) and then read integers using atoi

Resources