2. strcmp() in C++
Syntax: int strcmp ( const char * str1, const char * str2 );
Compare two strings
Compares the C string str1 to the C string str2.
This function starts comparing the first character of each string. If they are equal to each other,
it continues with the following pairs until the characters differ or until a terminating null-
character is reached.
This function performs a binary comparison of the characters.
3. Parameters & Return Value
Parameters:
str1
C string to be compared.
str2
C string to be compared.
return value indicates
<0
the first character that
does not match has a
lower value in ptr1 than
in ptr2
0
the contents of both
strings are equal
>0
the first character that
does not match has a
greater value in ptr1 than
in ptr2
Return Value:
Returns an integral value indicating the relationship between the
strings:
4. Example
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char str1[] = "Megadeth"; char str2[] = "Metallica";
// compare str1 and str2 lexicographically
int result = strcmp(str1, str2);
cout << result;
return 0;
}
// Output: -1
5. strcpy() function in C++
The strcpy() function in C++ copies a character string from source to destination.
It is defined in the cstring header file.
strcpy() Syntax
The syntax of strcpy() is: strcpy( char* dest, const char* src );
The behaviour of strcpy() is undefined if:
•The memory allocated for dest pointer is not large enough.
•The strings overlap.
6. Parameters & Return Value
Parameters:
The strcpy() function takes the following parameters:
•dest - pointer to a C-string where the contents are copied to
•src - pointer to a C-string where the contents are copied from
Return Value:
The strcpy() function returns:
•dest (the pointer to the destination C-string)
7. Example
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char src[20] = "I am the source.";
// large enough to store content of src
char dest[30] = "I am the destination.";
cout << "dest[] before copy: " << dest << endl;
// copy contents of src to dest
strcpy(dest,src);
cout << "dest[] after copy: " << dest;
return 0;
}
Output:
dest[] before copy: I am the destination.
dest[] after copy: I am the source.