#include
int compare( const string& str );
int compare( const char* str );
int compare( size_type index, size_type length, const string& str );
int compare( size_type index, size_type length, const string& str, size_type index2, size_type length2 );
int compare( size_type index, size_type length, const char* str, size_type length2 );
Sometimes, you want to compare two different strings for some reason. How do you compare strings in C++?
Easy, use the compare function defined in the string library. Look at all those function prototypes with the same header. I'm pretty sure this is called function overriding or overloading, when the same function name can have different parameters and handle these parameters differently. In this case we have variety of different functions with the same name, different parameters, but they all do the same thing in the end which is compare strings.
int compare( const string& str );
I have no idea what the parameters in the function above mean. Looks like this function has a single parameter: a constant string? I don't know what the ampersand is supposed to tell me! I just realized that I need to be more aware than I am about compare being a member function of the string type(class), therefore in order to use compare you have to create a string object and use a membership operator (e.i. a dot) between the object and the member function.
EXAMPLE SOURCECODE ON USING COMPARE WITH TWO STRINGS OH YAY:
string x = "blah";
string y = "nope";
int t;
t = x.compare(y);
cout<< see x.compare(y)
Darn. I finally understand. I just didn't think you had to declare what type of information was in the address. Now int compare( const string& str ); makes complete sense. This function accepts a constant string, but
instead of taking in a copy of the string, it takes the address of the string to compare the actual string and not a copy of the string. Fascinating!
if i were to create a function
int funct (int &y){
y = 10;
}
int main () {
int y = 5;
funct(y);
cout y; // psuedo code. add insertion operator.
the y variable would be changed and print 10 instead of 5. if i wouldn't have made the function accept the address of a the variable i'm passing to it then it would just create a copy of the variable, a local variable. try stuff out.
see http://www.cppreference.com/wiki/string/compare
i'm tired.
No comments:
Post a Comment