C++ PROGRAM Part 1) Answer the following exercise A) Implement a function named
ID: 3822126 • Letter: C
Question
C++ PROGRAM
Part 1) Answer the following exercise
A) Implement a function named startsWith which takes two string parameters str and start and returns true if str starts with start and false otherwise. e.g. santa monica, santa -> true The only string class functions you can use in your implementation are those to get string length and access its characters (no find function etc). Provide two examples of client code calling the function.
B) Same as part A, but the function is now endsWith and the second parameter is end.
Explanation / Answer
// C++ code
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string.h>
using namespace std;
bool startsWith(string str, string start)
{
// start length cannot be length of str
if(strlen(start.c_str()) > strlen(str.c_str()))
return false;
int len = strlen(start.c_str());
for (int i = 0; i < len ; ++i)
{
if(start[i] != str[i])
{
cout << "false ";
return false;
}
}
cout << "true ";
return true;
}
bool endsWith(string str, string end)
{
// end length cannot be length of str
if(strlen(end.c_str()) > strlen(str.c_str()))
return false;
int len = strlen(end.c_str());
int l = strlen(str.c_str());
for (int i = 0; i < len ; ++i)
{
if(end[i] != str[l+i-len])
{
cout << "false ";
return false;
}
}
cout << "true ";
return true;
}
int main()
{
string str = "santa monica clause";
string start = "santa";
string end = "clause";
startsWith(str,start);
endsWith(str,end) ;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.