Learn Computer Science programming - C# and C++ Algorithms

 

String Compare Implementation

Implementation of the strcmp function. The function strcmp compares two strings and returns either a negative number, zero, or a positive number depending on whether the first string was less than, the same as, or greater than the second string.
Code
stringcompare.zip
File Size: 1771 kb
File Type: zip
Download File

#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;

int StringCompare (char *str1, char *str2)
{
char *p1 = & str1[0];
char *p2 = & str2[0];
while (1)
{
if (*p1 != *p2)
return *p1 - *p2;
if (*p1 == '%%CONTENT%%' || *p2 == '%%CONTENT%%')
return 0;
p1++;
p2++;
}
}

void main()
{
int x;
wcout <<  endl << "*** String Compare ***" << endl;
wcout << "*************************************************" << endl;
char *d1 = "Hello World!";
char *d2 = "Hello Woorld!";
int h1 = StringCompare(d1,d2);

if (h1 > 0)
cout << "Result: " << h1 << " String : " << d1 << " Greater than " << d2 << endl;
else if (h1 < 0)
cout << "Result: " << h1 << " String : " << d1 << " less than " << d2 << endl;
else
cout << "Result: " << h1 << " Strings : " << d1 << " and " << d2 << " are equal." << endl;

char *d3 = "Heello World!";
char *d4 = "Hello World!";
int h2 = StringCompare(d3,d4);

if (h2 > 0)
cout << "Result: " << h2 << " String : " << d3 << " Greater than " << d4 << endl;
else if (h2 < 0)
cout << "Result: " << h2 << " String : " << d3 << " less than " << d4 << endl;
else
cout << "Result: " << h2 << " Strings : " << d3 << " and " << d4 << " are equal." << endl;

char *d5 = "Hello World!";
char *d6 = "Hello World!";
int h3 = StringCompare(d5,d6);

if (h3 > 0)
cout << "Result: " << h3 << " String : " << d5 << " Greater than " << d6 << endl;
else if (h3 < 0)
cout << "Result: " << h3 << " String : " << d5 << " less than " << d6 << endl;
else
cout << "Result: " << h3 << " Strings : " << d5 << " and " << d6 << " are equal." << endl;

cin >> x;
 }