Sunday, July 12, 2009

2.write a program in c to check if two string are same,dont use strings?

I will write steps to solve this problem. And I think, you will be able to solve this problem.





1) Get two strings (Input from user or any other source)


2) Compare the length of both strings. If length is not same, the strings are obviously different.


3) If above condition fails (means, the length of strings are same), write a loop (either for/while/do-while) and compare each character. Like 1st character of 1st string should be equal to 1st character of 2nd string and so on. If any of character is not matched, the strings are not the same.





We can use strcmp or similar function to do this. But your assignment is to not use this kind of functions, so u have to compare it in the way, i have described.

2.write a program in c to check if two string are same,dont use strings?
char string1[256];


char string2[256];





cin.getline(string1, 256);


cin.getline(string2, 256);





if(strcmp(string1, string2) == 0){


cout %26lt;%26lt; "Strings are equal";


}


else{


cout %26lt;%26lt; "Strings are not equal";


}
Reply:You can easily understand my code here (or already...).





bool CheckTwoStrings(char* str1,char* str2)


{





if(strlen(str1)!=strlen(str2)) return false;


/* If you don't want to use strlen, then here my strlen function below */





while(*str1!='\0')


{


if ((*str1)!=(*str2)) return false;


str1++;


str2++;


}





return true;





}





int strlen(char *p)


{


int i=0;


while(*p!=0)


{


i++;


p++;


}


return i;


}





then, i think it's almost up...


If you got anything not clear or better suggestion, then please call me... cruisernk@yahoo.com
Reply:Well, without using string class just compare them as ordinary arrays.. First the size (if it doesn't match then they can't be the same) and afterwards character by haracter...
Reply:All the above answers are correct. I would like to add that if you are not using strings, declare the variable as an array of characters. For example, char[20]....etc. Then, you can compare the two strings, character by character, using just one loop!


Hope this helps!


Good Luck!

magnolia

No comments:

Post a Comment