Originally Posted by
motionman95
Is is done like this? I can't get it to work.
Code:
if(char[] == "I love cheese."){
}
Don't we wish!
A char is a single letter or digit, so no go. Strings in C *must* be elevated to string status by the use of the end of string marker: '\0'.
This:
char *string = {"I love cheese"};
has the end of string marker automatically applied to it. Certain string functions will do this, as well. scanf() and fscanf() are two that come first to mind. fgets() will, if there is room for it.
Anyway, to compare strings in C:
Code:
if(strcmp(string1, string2) == 0) //strings match
if(strcmp(string1, string2) > 0) //string1 is greater
if(strcmp(string1, string2) < 0) //string2 is greater
result = strcmp(string1, string2); //can be used this way, as well
if(result == 0)
//strings are a match
else if(result > 0) //string1 is greater
else
//string2 is greater
You'll need to include the header file <string.h>, (usually, compiler's vary) to use strcmp().
If you only need to /want to compare the first N char's of each string, then you can use the "sister" function strncmp().
Pretty spiffy, eh?