|
-
Jun 30th, 2002, 03:52 PM
#1
compare two String ?
In java we have .equals()
but in C++ I can not find it ? I have tryed strcmp but it doesn't work.
Any suggestion?
-
Jun 30th, 2002, 03:57 PM
#2
PowerPoster
strcmp should work. What code are you using?
PHP Code:
if(strcmp(string1, string2) == 0)
{
cout<<"Both strings are same";
}
-
Jun 30th, 2002, 04:08 PM
#3
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
-
Jun 30th, 2002, 04:09 PM
#4
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 *'
-
Jun 30th, 2002, 04:11 PM
#5
Fanatic Member
If you're using the C++ string class you can just do:
PHP Code:
if (str1 == str2)
{
cout << "Equal" << endl;
}
Alcohol & calculus don't mix.
Never drink & derive.
-
Jun 30th, 2002, 04:14 PM
#6
Wynd thx it's work now but I am wondering why the other solution didn't work ?
-
Jun 30th, 2002, 04:30 PM
#7
Fanatic Member
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.
Alcohol & calculus don't mix.
Never drink & derive.
-
Jun 30th, 2002, 04:55 PM
#8
PowerPoster
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";
}
-
Jul 2nd, 2002, 03:33 AM
#9
Junior Member
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|