I need help writing the function for this RME in C++ using c-strings! // REQUIRE
ID: 3881775 • Letter: I
Question
I need help writing the function for this RME in C++ using c-strings!
// REQUIRES: str1 and str2 point to C-strings
// EFFECTS: If str1 and str2 contain exactly the same characters, returns 0.
// Otherwise, return a positive number if the first differing char // has a greater value in str1 than in str2 and a negative number in
// the opposite case (you may NOT call strcmp).
int strcmp(const char *str1, const char *str2)
{ So what I figured is that I have to compare the two strings, assuming they are the same length.
if (str1 == str2) { return 0; }
else { //somehow compare every letter and when the letters at the same index are not equal, return the difference of the letter in str1 - the letter in str2 so if str1 is greater it returns a positive number and a negative one if the differing letter in str1 is smaller than the one in str2. }
Explanation / Answer
#include <iostream>
using namespace std;
int strcmp(const char *str1, const char *str2) {
if (str1 == str2) {
return 0;
}
else {
int n =0;
while(str1[n]!=''){
n++;
}
for(int i=0;i<n;i++) {
if(str1[i] != str2[i]) {
if(str1[i] > str2[i]) {
return 1;
} else {
return -1;
}
}
}
}
}
int main()
{
char str1[100] ="Hai", str2[100]="Hello";
cout<<"Result: "<<strcmp(str1, str2)<<endl;
return 0;
}
Output: