C strcmp() with one char difference - c

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.

Related

Confusion with usage of strcmp() for number strings

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

strcmp isn't comparing strings properly [duplicate]

This question already has answers here:
strcmp behaviour in 32-bit and 64-bit systems
(3 answers)
Closed 9 years ago.
So I have this (not the full code)
char list[1000][10];
strcpy(list[0],"ab");
printf("%d\n",strcmp(list[0],"ab"));
and the strcmp is returning 0. Can somebody explain why it's doing so?
Thanks in advance.
The strcmp method will return 0 if list[0] contains "ab" in this case.
It returns:
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; And a value less than zero indicates the opposite.
strmp returns 0 when the strings match. Unless I am missing something, it's behaving as expected.
see: http://www.tutorialspoint.com/ansi_c/c_strcmp.htm
strcmp() does an ordinal comparison of the strings, not an equality test. The return value of 0 means the strings are equal!
If you want to test for equality use this pattern:
if (strcmp(s, "ab") == 0) {
// strings are equal
}
Because strcpy() is a function that copies the "right" string to the "left" string.
So, after strcpy(list[0],"ab");, the content of list[0] is "ab".
Then, they are equal strings, and strcmp returns 0, which means "equal".
Your String is matched that is why it is returning 0
do like this...
char list[1000][10];
strcpy(list[0],"ab");
if(strcmp(list[0],"ab")==0)
printf("Matched\n",);
As mentioned by Daniel, the returnd value is 0.
Taken from cplusplus.com
Returns an integral value indicating the relationship between the
strings: A zero value indicates that the characters compared in both
strings form the same string. A value greater than zero indicates
that the first character that does not match has a greater value in
str1 than in str2; And a value less than zero indicates the opposite.
You should also work with strncmp rather than with strcmp.

How strcmp() is returning -1 even though the two values are same?

When I am giving an input as 'x' the compVal is giving the value as -1. I am expecting 0 since both the values are same. Please someone explain the reason.
char ch = getchar();
int compVal = strcmp("x", &ch);
You have to give to strcmp two strings. A string is an array of char with the last value being \0.
In your example, the second value you are passing it is just the address of a char and there is no string terminator so the function goes blindly ahead until it finds a 0 ( same thing as \0).
You should either use strcmp with a char vector like char ch[2] ( One value for the character you want and the other for the \0 I mentioned earlier or, in your case you should just use the == operator since you want to compare only one character.
You probably shouldn't be using strcmp() to compare single characters.
Char variables can just be compared using relational operators such as ==, >, >= etc
I would think the reason that you're comparison isn't working is that you're comparing a string to a single character. Strings have a null terminator "\0" on the end of them, and it will be added if it isn't there. Therefore string compare is correctly telling you that "x\0" is not equal to "x".
strcmp reads from the input address untill a \0 is found. So you need to provide NULL terminated strings to strcmp. Not doing so results in Undefined behavior.
These are two different data types.
Remember that internally "x" is stored as 'x' and '\0' in memory. You need to make memory look the same for it to work as a string in C.
This will work:
char ch[2];
ch[0] = getchar();
ch[1] = 0;
int compVal = strcmp("x",ch);
Here you compare two arrays of characters. Not an address of a single char and a char*.
You compare the constant string "x" with a char 'x'. By giving the pointer to that char your make strcmp think it is comparing strings. However, the constant string "x" ends with '\0' but the char you use as a string does not end with '\0', which is a requirement of a string.
x\0
x ^ <- difference found
However, what you are doing might result in a segmentation fault on other systems. The correct fix for this is to put a terminating null character after the input or just compare the chars (in this case that is even better!).
You can compare characters directly:
char ch = getchar();
if ('x'==ch)
{
/* ... */
}

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.

Resources