In C++ please, Write a program that implements and tests the following functions
ID: 3770167 • Letter: I
Question
In C++ please,
Write a program that implements and tests the following functions for use with C-strings without using the C-string library (that is, you are NOT ALLOWED to use #include <cstring> in this program):
int strcompare(const char *s1, const char *s2);
The strcompare function performs a comparison of s1 to s2. It starts with the first character in each string and continues with subsequent characters until the corresponding characters differ or until the end of the strings is reached. strcompare returns a value that is:
< 0 if s1 is less than s2,
== 0 if s1 is the same as s2, or
> 0 if s1 is greater than s2.
More precisely, if the strings differ, the value of the first nonmatching character in s2 subtracted from the corresponding character in s1 is returned.
unsigned long strlength(const char *str);
The strlength function calculates the length of str. Returns the number of characters in str, not counting the terminating null character.
Example run (with user input indicated with bold italics):
Enter string 1: cats rule
Enter string 2: DOGS DROOL
string 1 is 9 characters long.
string 2 is 10 characters long.
string 2 lexicographically comes before string 1.
Explanation / Answer
#include <iostream>
#define MAX 1000
using namespace std;
int strcompare(const char* s1,const char* s2)
{
int i;
for(i=0;s1[i]!=''||s2[i]!='';i++)
if(s1[i]!=s2[i])
return s1[i]-s2[i];
return 0;
}
unsigned long strlength(const char *str)
{
unsigned long i;
for(i=0;str[i]!='';i++);
return i;
}
int main() {
char str1[MAX],str2[MAX];
cout<<"Enter string 1:";
cin.getline(str1,MAX);
cout<<"Enter string 2:";
cin.getline(str2,MAX);
cout<<"string 1 is "<<strlength(str1)<<" characters long ";
cout<<"string 2 is "<<strlength(str2)<<" characters long ";
if(strcompare(str1,str2)==0)
cout<<"string 1 and string 2 are equal ";
else if(strcompare(str1,str2)<0)
cout<<"string 1 lexicographically comes before string 2 ";
else
cout<<"string 2 lexicographically comes before string 1 ";
return 1;
}