1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
#include <iostream>
using namespace std;
// Implement the following function prototypes
int stringLength1 (const char *str);
int stringLength2 (const char *str);
char* stringCopy1 (char *str1, char *str2);
char* stringCopy2 (char *str1, char *str3);
char* stringCat1 (char *str1, char *str2);
char* stringCat2 (char *str1, char *str3);
// Use the following driver to test implementations:
int main()
{
char str1[20];
char* str2 = "Forrest";
char* str3 = "Run";
// Test stringLength functions
cout << "stringLength1 (" << str2 << "): "
<< stringLength1 (str2) << endl;
cout << "stringLength2 (" << str3 << "): "
<< stringLength2 (str3) << endl;
// Test stringCopy functions
cout << "stringCopy1 (str1, " << str2 << "): "
<< stringCopy1 (str1, str2) << endl;
cout << "stringCopy2 (str1, " << str3 << "): "
<< stringCopy2 (str1, str3) << endl;
// Test stringCat functions
cout << "stringCat1 (str1, " << str2 << "): "
<< stringCat1 (str1, str2) << endl;
cout << "stringCat2 (str1, " << str3 << "): "
<< stringCat2 (str1, str3) << endl;
system("pause");
return 0;
} // end main
//Determines the length of string str. The number of characters preceding the terminating null character is returned.
int stringLength1(const char* str)
{
int counter = 0;
while(str[counter] != '\0')
{
counter++;
}
return counter;
}
int stringLength2 (const char *str)
{
int counter = 0;
while(str[counter] != '\0')
{
counter++;
}
return counter;
}
//Copies the string str2 into the character array str1. The value of str1 is returned.
char* stringCopy1 (char *str1, char *str2)
{
str1 = str2;
return str1;
}
char* stringCopy2 (char *str1, char *str3)
{
str1 = str3;
return str1;
}
//Appends a copy of string str2 to string str1. The first character of str2 overwrites the terminating null character of str1. The value of str1 is returned.
char* stringCat1 (char *str1, char *str2)
{
char *cat = '\0';
*cat = *str1 + *str2;
return cat;
}
char* stringCat2 (char *str1, char *str3)
{
char *cat = '\0';
*cat = *str1 + *str3;
return cat;
}
|