Tuesday, July 14, 2009

Is there a way, in the C language, to compare individual parts of different strings?

I am trying to program just a simple hangman game, and when I wanted to compare the users guess to the string which was the word, I thought this would work...





if (guess==word[i])...





with guess being their input and word[ ] being the string that is the word they are trying to guess. But my compiler had an issue with this, saying that I was passing the getche() function too many arguments. Does anyone know of a proper/better way to compare individual parts of a string to a character? Thanks.

Is there a way, in the C language, to compare individual parts of different strings?
http://www.cppreference.com/stdstring/st...


http://www.die.net/doc/linux/man/man3/st...
Reply:well you can do if(guess[i]==word[i]) ?





example:





%26lt;stdio.h%26gt;


int main() {


char buffer[256];


printf("richest man in the world: _ _ _ _ _ _ _ _ _");


scanf("%s", %26amp;buffer);


char *answer="bill gates";





if(buffer[i]==answer[i]) {


correct execution


i++;


} else {


do w.e


}


}





I dun recommend you use this coding style tho as its messy you will end up with huge code density and it totally kills any way to expand... just wrote this to show an example and didn't even attempt to compile it... good luck.





theres also the strcmp function...





strcmp("test", input);








"But my compiler had an issue with this, saying that I was passing the getche() " %26lt;%26lt;%26lt; this has nothing to do with how your comparing the strings tho ... its complaining about getchar() having too many arguments... read the docs for getchar() an d make sure your calling it correctly.
Reply:You can use the strcmp() function to compare the entire string. However, if you need to compare parts of string, then you must remember that string in C is stored in the form of array of characters. Then you can use the loop as follows:


int streq=1;


for(i=start;i%26lt;end;i++)


{


if(s1[i]!=s2[i])


{


streq=0;


break;


}


}


if(streq) printf("String are equal');


else printf("Strings are not equal");





Remember that st1 and st2 are the two strings and start and end are the starting and ending points of the string.
Reply:of course, but using string compare function which is strcomp





for example





if (strcomp(string1, string2) == 0)


// this means if the two strings are equal





if (strcomp(string1, string2) == 1)


// this means if the two strings are not equal
Reply:its simple just use


scanf("%c",%26amp;guess);


use this statement for accepting a guess character and the program will work thank you and use the same loop and in loop use this statement


if(guess==a[i])


this will work now thank you oh and yeah the string compare function is strcmp and strcmpi where strcmpi is not case sensitive and it is not strcomp


No comments:

Post a Comment