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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
|
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cstring>
// return length of null-terminated string stored in char array
int myStrLen(const char[]);
// copy the contents of the 2nd string into the 1st
void myStrCpy(char[], const char[]);
// return 0 if two strings are equal, else return 1
int myStrCmp(const char[], const char[]);
int main()
{
cout << endl;
char text[128]; // to read any string
// prompt user to enter word or phrase
cout << "Please enter a word or phrase followed by the enter key: ";
cin.getline(text, 128);
char input[128]; // set up storage for users input
myStrCpy(input, text);
char abc[] = "ABC"; // string for comparison
cout << endl;
cout << "String: " << text << endl; // output what they entered
cout << "Length: " << myStrLen(text) << endl; // output the length of input
if (myStrCmp(text, abc) == 0) // compare their input vs comparison string
{
// output whether or not it is equal to comparison string
cout << "Your string equals ABC" << endl << endl;
}
else
{
cout << "Your string does not equal ABC" << endl << endl;
}
// change the string, print it, and compare it
myStrCpy(text, "ABC");
cout << "String: " << text << endl;
cout << "Length: " << myStrLen(text) << endl;
if (myStrCmp(text, abc) == 0)
{
cout << "The changed string equals ABC" << endl << endl;
}
else
{
cout << "The changed string does not equal ABC" << endl << endl;
}
strcpy(text, input);
//print the string and compare it
cout << "String: " << text << endl;
cout << "Length: " << strlen(text) << endl;
if (strcmp(text, abc) == 0)
{
cout << "Your string equals ABC" << endl << endl;
}
else
{
cout << "Your string does not equal ABC" << endl << endl;
}
//change the string, print it, and compare it
strcpy(text, "ABC");
cout << "String: " << text << endl;
cout << "Length: " << strlen(text) << endl;
if (strcmp(text, abc) == 0)
{
cout << "The changed string equals ABC" << endl << endl;
}
else
{
cout << "The changed string does not equal ABC" << endl << endl;
}
return 0;
}
int myStrLen(const char text[])
{
int array = 0;
for (int i = 0;; i++)
{
if (text[i] == '\0')
break;
array++;
}
return array;
}
void myStrCpy(char text[], const char abc[])
{
// no need for temp variable.
int i;
for(i = 0; abc[i] != '\0'; i++)
text[i] = abc[i];
text[i] = '\0'; // c-strings end with a nul character.
}
int myStrCmp(const char text[], const char abc[])
{
int y;
int x = 0;
while (text[x] != '\0' && abc[x] != '\0')
{
y = 0;
x++;
}
y = 1;
return y;
}
|