Lab #12. C-style string processing in functions
Lab #12.1.
String copying
Function strcpy() available in <cstring>
library – copies the contents of source string src to destination string dest (lab11.1.cpp).
#include <iostream>
using namespace std;
char *strcpy2 (char *dest,
const char *src)
{
// ADD CODE HERE
};
int main()
{
char s1[20] =
"first";
char s2[20] =
"second";
cout
<< s1 << endl << s2 << endl;
strcpy
(s1, s2);
//strcpy2 (s1, s2);
cout
<< s1 << endl << s2 << endl;
return 0;
}
Create your
own strcpy2() to imitate strcpy(). A technical feature of this function is to return the new
string both through parameter and return statement (return type: char*):
char *strcpy2 (char *dest,
const char *src)
const before the second parameters guarantees it
not to be changed in the function.
It is assumed that there exists an array of enough size in memory for
string dest.
A correct solution: lab11.1a.cpp.
Lab #12.2.
String concatenation
Function strcat() (string concatenation) available in
<cstring> library – copies all characters of source
string src
to the end of destination string dest (lab11.2.cpp).
#include <iostream>
using namespace std;
char *strcat2 (char *dest,
const char *src)
{
// ADD CODE HERE
};
int main()
{
char s1[20] =
"first";
char s2[20] =
"second";
cout
<< s1 << endl << s2 << endl;
strcat
(s1, s2);
//strcat2 (s1, s2);
cout
<< s1 << endl << s2 << endl;
return 0;
}
Create your
own strcat2() to imitate strcat(). A technical feature of this function is to return the new
string both through parameter and return statement (return type: char*):
char *strcat2 (char *dest,
const char *src)
A correct solution: lab11.2a.cpp.
Lab #12.3.
String comparison
Function strcmp() available in <cstring>
library – compares two string on equality (lab11.3.cpp).
#include <iostream>
using namespace std;
int strcmp2 (const char
*s1, const char *s2)
{
// ADD CODE HERE
};
int main()
{
char s1[20] =
"first";
char s2[20] =
"second";
char s3[20] =
"first";
char s4[20] =
"firs2";
cout
<< strcmp (s1, s2) << endl;
cout
<< strcmp (s2, s1) << endl;
cout
<< strcmp (s1, s3) << endl;
cout
<< strcmp (s1, s4) << endl;
/*cout <<
strcmp2 (s1, s2) << endl;
cout
<< strcmp2 (s2, s1) << endl;
cout
<< strcmp2 (s1, s3) << endl;
cout
<< strcmp2 (s1, s4) << endl;*/
return 0;
}
Create your
own strcmp2() to imitate strcmp(). If both strings are equal, function returns 0, otherwise -1 or
1 (-1, if the first string is lexically smaller; 1, if greater):
char *strcmp2 (const
char *s1, const char *s2)
A correct solution: lab11.3a.cpp.