How does strcmp work when comparing strings? - c

I am implementing a lexicographic sort and my professor told us to use strcmp in our implementation. The problem is, strcmp is very confusing in respects to how it compares strings.
For instance, this here yields false:
if (strcmp("What", "am") > 0) {
printf("true\n");
} else {
printf("false\n");
}
Isn't "What" suppose to be greater than "am" lexicographically? The man page is very spartan in terms of explaining how the function determines if one string is greater or less than the other. There are some questions here, but I still cannot determine this result based on those explanations.

The problem is that strcmp makes a binary comparison. This fact makes the function case sensitive! The ASCII code of "W" is smaller than the ASCII code of "a".
The way to solve the problem is to compare text strings that as the same capitalization.
A simple way to obtain this shall be:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char* stoupper( char* s )
{
char* p = s;
while (*p) {
*p= toupper( *p ); p++
};
return s;
}
int main(void)
{
char a[10];
char b[10];
strcpy(a,"What");
strcpy(b,"am");
if (strcmp(stoupper(a), stoupper(b)) > 0) {
printf("true\n");
} else {
printf("false\n");
}
}
Remember that the use of the function stoupper modifies definitively the text in the string!

Any capital letter compare less than any lowercase one. Look at an ASCII chart and the definition of lexicographical comparison.

My guess is that this is because 'W' comes before 'a' in the ascii table. So 'What' is actually 'lesser' than 'am'.
If you switch them I guess 'am' is 'greater' than 'What'.

Related

How to compare two characters without case sensitivity in C?

I am trying to compare two specific characters in two strings,but I want to make the comparing without case sensitivity. How can I do this?
right now I am using a code like that:
if (str1[i]==str2[j]) printf("Equal");
but I want to do this without case sensivity.
Thank you in advance for taking your time to help!
You can use low case for both chars, for example by using tolower function:
if (tolower(str1[i])==tolower(str2[j])) printf("Equal");
Also keep in mind: tolower does not work for multibyte char. So for those chars you should use other function
We can achieve your requirement by converting both of the character to either upper or lower case character using toupper() or tolower().
Example:
#include <stdio.h>
#include <ctype.h> //For tolower()
int main()
{
char str1[]="Time", str2[]="time";
/*
* Just for an example i am comparing the first char
* from 2 different strings.
*/
if(tolower(str1[0]) ==tolower(str2[0])) {
printf("Char's are equal\n");
}
else {
printf("Char's are not equal");
}
return 0;
}
Output:
Char's are equal

Program keeps returning Segmentation Fault [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm a new person who loves to play around with coding. Recently I was going through a course on edx, and one of the exercises I need to complete has this small code snippet that keeps on giving Segmentation fault. I have taken out the faulty bit (everything else compiles nicely)
#include <stdio.h>
#include <string.h>
#include <cs50.h>
#include <ctype.h>
#include <stdlib.h>
int main (int argc, string argv[])
{
if (argc == 2 && isalpha(argv[1]))
{
int a = 0;
while (argv[1][a] == '\0')
{
a++;
printf("%c\n", argv[1][a]);
}
}
else
{
printf("Usage: ./programname 1-alphabetical word\n");
return 1;
}
}
The problem seems to be here: argv[1][a] but I can't for the life of me find out what, and how to fix it.
(1) isalpha(argv[1]) is wrong. This function expects a single character, but you are passing a pointer-to-string. That will certainly not give you any kind of expected result, and it's probably Undefined Behaviour into the bargain. You either need to loop and check each character, use a more high-level library function to check the entire string, or - as a quick and probably sense-changing fix - just check the 1st character as BLUEPIXY suggested: isalpha( argv[1][0] ) or isalpha( *argv[0] ).
(2) Your while condition is wrong. You are telling it to loop while the current character is NUL. This will do nothing for non-empty strings and hit the next problem #3 for an empty one. You presumably meant while (argv[1][a] != '\0'), i.e. to loop only until a NUL byte is reached.
(3) You increment index a before trying to printf() it. This will index out of range right now, if the input string is empty, as the body executes and then you immediately index beyond the terminating NUL. Even if the loop condition was fixed, you would miss the 1st character and then print the terminating NUL, neither of which make sense. You should only increment a once you have verified it is in-range and done what you need to do with it. So, printf() it, then increment it.
2 and 3 seem most easily soluble by using a for loop instead of manually splitting up the initialisation, testing, and incrementing of the loop variable. You should also use the correct type for indexing: in case you wanted to print a string with millions or billions of characters, an int is not wide enough, and it's just not good style. So:
#include <stddef.h> /* size_t */
for (size_t a = 0; argv[1][a] != '\0'; ++a) {
printf("%c\n", argv[1][a]);
}
isalpha(argv[1]) looks incorrect and should probably be isalpha(argv[1][0])
isalpha takes a character but you entered in a string to the function
another thing that sticks out as wrong is argv[1][a] == '\0' the ==
should be != this will mean that the while loop will stop once it hits the \0
perhaps
if (argc == 2)
{
int a = 0;
while (argv[1][a] != '\0')
{
if (isalpha(argv[1][a])
printf("%c\n", argv[1][a]);
a++;
}
}
may be what you are looking for?
The only reason for the segmentation fault I see is this subexpression of the if statement
if (argc == 2 && isalpha(argv[1]))
^^^^^^^^^^^^^^^^
There is specified an argument of an incorrect type. The expression argv[1] has the type char * while the function requires an object of character type that is interpreted as unsigned char and promoted to the type int.
So when the promoted argument has a negative value (except the EOF value) the function isalpha has undefined behavior.
From the C Standard (7.4 Character handling <ctype.h>)
1 The header <ctype.h> declares several functions useful for
classifying and mapping characters.198) In all cases the argument is
an int, the value of which shall be representable as an unsigned
char or shall equal the value of the macro EOF. If the argument has
any other value, the behavior is undefined.
You should write the if statement either like
if (argc == 2 && isalpha( ( unsigned char )argv[1][0] ) )
or like
if (argc == 2 && isalpha( ( unsigned char )*argv[1] ) )
Also there is a bug in the while statement that will execute never if the argument is not an empty string. I think you mean the following
int a = 0;
while ( argv[1][a] != '\0' )
{
printf("%c\n", argv[1][a]);
a++;
}
or for example like
int a = 0;
while ( argv[1][a] )
{
printf("%c\n", argv[1][a++]);
}

Searching for an element in 2D array, C programming

I'm a noob at C programming and I'm having some difficulties making a string list and searching for a specific element.
#include <stdio.h>
#include <string.h>
# define MAX 6
int main(){
char word[MAX];
char x[MAX][20];
int i;
strcpy(x[0], "One");
strcpy(x[1], "Two");
strcpy(x[2], "Three");
strcpy(x[3], "Four");
strcpy(x[4], "Five");
strcpy(x[5], "Six");
printf("%s", "Search:");
scanf("%s", word);
for (i=0; i<6; i++) {
if (x[i] == word) {
printf("%s", "Found a match!");
}
}
return 0;
}
It's never executing the statement present in the if block (i.e, printf("Found a match!")) . Any idea why it is not executing the above mentioned statement?
Thanks!
Use
if(strcmp(x[i],word) == 0)
printf("Found match\n");
== can't be used to compare strings as you are doing it.
This only compares the pointers and not the strings
It never returns "Found a match!". Any idea why?
Reason:
In C, array names are converted to pointers to their first elements ( with some exceptions there). x[i] == word is comparing two pointers instead of comparing strings. Since the base addresses of both arrays are different, comparison returns a false value.
Correction:
Use strcmp to compare two strings.
This
if (x[i] == word)
should be
if (strcmp(x[i], word) == 0)
In c a predefined function is present in string.h library it is strcmp as stated by other users function int strcmp(const char *str1, const char *str2) compares the string pointed to bystr1 to the string pointed to by str2.u can write your own function for comparing strings and use it.
I want you to conceptually understand why we can't use == in c unlike c++ as c don't contain anything like string class(c is purely procedural) so that u can create object of it and use it.hence c uses char array to represent a string .if u examine ur code x[i] == word compares starting addresses of char arrays/strings x[i],word. I believe u understood the concept . now I want to explain that u can use pointers here i.e
if (*x[i] == *word)
printf("Found a match!");
Works fine as u can understand that here we are comparing two strings directly by pointing to their address locations.sorry if I have provided unwanted info due to my inexperience in SO as this my first answer in SO.
use strcmp() function for comparing two string. when two string is match its result is 0.
so you can change like :
if ( ! strcmp(word,x[i]) ) // when match result will be `! 0 = 1`
printf("Found Match\n");
in the C programming language, the == operator is not working for comparing strings(as others wrote before me). I advice to try using a really nice feature in C++ called string. It is builded in the standard library, and with this, you can use the == operator for comparing.
#include <iostream>
using namespace std;
int main(void)
{
string a = "Apple";
if( a == "Apple" ) cout << "This is working" << endl;
}

The following code for palindrome doesn't work?is there a logical mistake?

Could someone point me to the error in this code. Iam using codingblocks IDE.
#include <stdio.h>
main()
{
char a[100],b[100];int i,j=0;
scanf("%s",&a);
for(i=strlen(a)-1,j=0;i>=0;i--)
{
b[j]=a[i];
j=j+1;
}
b[j]='\0';
if(a==b) # on printing i get both 'a' and 'b' as equal however this condition still remains
# false
printf("true"); #doesnot print?
}
Change this statement
if(a==b)
to
if ( strcmp( a, b ) == 0 )
Otherwise you are comparing addresses of the first elements of the arrays.
Also you need to include header <string.h>. Function main shall have return type int. Change this statement
scanf("%s",&a);
to
scanf( "%s", a);
Take into account that there is no need to define second array that to determine whether a string is a palindrome. You could do this check "in place".
Few issues in your code
You never copy anything in b, so that array has random characters.
a==b will always be false because they are character arrays not pointers and both contain different values.
If you are reading string, you don't need & for char array, so the scanf() should be scanf("%s",a);

Begginger, string in switch in C with sourcecode. Possible?

So basically I wanted to create a program in C, in wich you would input 2 character long string (mix of letter and noumber ex.r1,u2,i3,i4,r6) to be the input in my program. Later I want to put this string in SWITCH. Is this possible?
Here's my simple sourcecode. Please correct me on any mistakes :)
#include <stdio.h>
int main(void)
{
char string[2];
scanf("%s", &string);
switch (string)
{
case 'u1' :printf("%s\n", string);break;
default :printf("ERROR");break;
}
return 0;
}
Create a code based on the string and switch on that.
#define Code(a,b) (a + 256*b)
char string[3]; // 3 not 2
if (scanf("%2s", string) != 1) { // No &
Handle_Error();
}
int scode = Code(string[0], string[1]);
switch (scode) {
case Code('u', '1') : printf("%s\n", string); break;
case Code('r', '2') : printf("r2\n"); break;
...
default :printf("ERROR");break;
}
A switch(x) needs an integer value for x and string is an array. So the original approach will not work.
The program can use an integer based on the string for x and use the same method for generating the case values. Since there is only the first 2 char of the string are of interest, the int value is unique.
No, this is not possible. Switch only works with integral types in C (int, short, long, etc, as well as types defined with enum).
You can however use a simple if-else construct to get the same behavior:
if (strcmp(string, "ui" ) == 0) //test for string equality
{
printf("%s\n", string);
}
else
{
printf("ERROR")
}
We use strcmp instead of == because we are dealing pointers which almost certainly not compare equal even when the two strings have the same content.
strcmp(str1, str2) == 0 is the standard idoim in C for comparing two strings.
strcmp returns an integer representing how two strings compare to each other. 0 means they are equal, a negative number means that the first string is lexographically "less than" the second, and a positive number means that the first string is lexographically "greater than" the second. More info can be found here.
A switch won't work here.
You need to use an if/else if construct and strcmp to compare the strings.
Also, you need at least 3 characters in your input array so that it can hold the two input characters and the terminating null character.
Of course, such a small buffer can easily overflow.

Resources