In java we have .equals()
but in C++ I can not find it ? I have tryed strcmp but it doesn't work.
Any suggestion?
Printable View
In java we have .equals()
but in C++ I can not find it ? I have tryed strcmp but it doesn't work.
Any suggestion?
strcmp should work. What code are you using?
PHP Code:if(strcmp(string1, string2) == 0)
{
cout<<"Both strings are same";
}
int CompareString(
LCID Locale, // locale identifier
DWORD dwCmpFlags, // comparison-style options
LPCTSTR lpString1, // pointer to first string
int cchCount1, // size, in bytes or characters, of first string
LPCTSTR lpString2, // pointer to second string
int cchCount2 // size, in bytes or characters, of second string
);
That thing doesnt work let me try your code
Here is the error I got with your code :
Code:error C2664: 'strcmp' : cannot convert parameter 1 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'const cha
r *'
If you're using the C++ string class you can just do:
PHP Code:if (str1 == str2)
{
cout << "Equal" << endl;
}
Wynd thx it's work now but I am wondering why the other solution didn't work ?
Because all the functions in <cstring> are for use with the character array strings from C. So basically, there is no function that matches strcmp(string, string) so it spits out an error.
Because String is a class and strcmp only uses a "char" type. So it won't accept any parameter that's declared as String.
But the member function "c_str()" of String will return the string as a character array that you can use with strcmp.
You can also do like this but Wynd's solution is easier:
PHP Code:if(strcmp(string1.c_str(), string2.c_str()) == 0 )
{
cout<<"Both strings are same";
}
If I am not mistaken, the strcmp(); function's return value is extremenly useful. THis is slightly off-topic, but you can use the return value to know wether string1 is less than or greater than string2, alphabetically.
If you have char arrays, experiment with that a bit. I think if the return value is less than 0, string1 < string2, 0 means string1 == string2, and greater than 0 means string1 > string2.