String Compare Function
Sep 22, 2012 at 5:30am UTC
Come with dumb question again :(
Program is a C function to compare a string to another for equality of content.
Function prototype:
int myStrCmp(const char[], const char[]); // return 0 if two strings are equal, else return 1
No pointer
No <Cstring>
What I wrote is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
using std::cout;
using std::endl;
//prototype
int myStrCmp(const char [], const char []);
int main()
{
const char *str = "Hello" ;
const char test[100000]="World" ;
cout<<"Test: " <<test<<endl;
if (myStrCmp(test,str)==0)
{
cout<< "Same" ;
}
else
{
cout<< "Different" ;
}
}
int myStrCmp(const char test[], const char str[])
{
int i;
int res;
int temptest,tempstr;
for (i = 0; str[i] != '\0' ;i++)
{
temptest=test[i];
tempstr=str[i];
res=tempstr-temptest;
if (res!='0' );
{
break ;
}
return 1;
}
return 0;
}
No matter what I put into
const char test[100000]="World" ;
, The result is always
.
I am thinking the return part has problems, or maybe the whole function is wrong :(
Can anyone tell me how to fix it?
Last edited on Sep 22, 2012 at 5:33am UTC
Sep 22, 2012 at 5:45am UTC
You did lots of small and silly programming mistake i corrected your code and posting it here. hope will useful to you..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int myStrCmp(const char test[], const char str[])
{
int i;
int res;
int temptest,tempstr;
for (i = 0; str[i] != '\0' ;i++)
{
temptest=test[i];
tempstr=str[i];
res=tempstr-temptest;
if (res != 0) // no coma
{
return 1;
}
}
return 0;
}
Sep 22, 2012 at 5:51am UTC
lol Thank you so much! You are right...they are stupid mistake.....
Topic archived. No new replies allowed.