(Program in C++) Using only pointer notation, implement and test the following f
ID: 3882763 • Letter: #
Question
(Program in C++) Using only pointer notation, implement and test the following functions that operate on strings:
int strCmp ( const char *s1, const char *s2) returns 0 if s1 and s2 are the same; it returns-1 when s1 precedes alphanumerically s2 or it returns 1 when s1 follows alphanumerically s2.
char * strPbrk (const char*s1, const char*s2) scans s1 for the first occurrence of any character appearing in s2 and returns a pointer to its location or NULL if no such occurrence is found.
char* ItoA ( int n, char*s) converts an integer n into string of numerals stored in s and returns s.
Explanation / Answer
#include <iostream>
using namespace std;
int strCmp ( const char *s1, const char *s2)
{
while(*s1 && *s2)
{
// s1 preceeds s2
if(*s1>*s2)
{
return 1;
}
// s1 preceeds s2
else if(*s1 < *s2)
{
return -1;
}
// increasing by 1
else{
*s1++;
*s2++;
}
}
return 0;
}
int main() {
// sample runs
cout << strCmp ( "aaabc", "aabc") << endl;
cout << strCmp ( "aabc", "aaabc") << endl;
cout << strCmp ( "aaabc", "aaabc") << endl;
}
#include <iostream>
using namespace std;
int strCmp ( const char *s1, const char *s2)
{
while(*s1 && *s2)
{
// s1 preceeds s2
if(*s1>*s2)
{
return 1;
}
// s1 preceeds s2
else if(*s1 < *s2)
{
return -1;
}
// increasing by 1
else{
*s1++;
*s2++;
}
}
return 0;
}
int main() {
// sample runs
cout << strCmp ( "aaabc", "aabc") << endl;
cout << strCmp ( "aabc", "aaabc") << endl;
cout << strCmp ( "aaabc", "aaabc") << endl;
}
Sample Output -1 1 0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.