Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C ++ PROGRAMMING (DON\'T COPY THIS @ chegg users. If anyone copies this, change

ID: 3822977 • Letter: C

Question

C ++ PROGRAMMING

(DON'T COPY THIS @ chegg users. If anyone copies this, change it up please or ask your own question )

PART 1

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 question 1 but the function is now endsWith and the second parameter is end.

c) Implement a function named replaceAll which takes a string str and two characters oldChar and newChar as parameters. It replaces all occurrences of oldChar in the string with newChar. The function returns nothing. Provide an example of client code calling the function.

d) Implement a function named reverse which takes a string and reverses it. The function returns nothing. Provide an example of client code calling the function.

Explanation / Answer

#include <iostream>
using namespace std;

// Function to reverse a string
void reverse(string &str)
{
int n = str.length();

// Swap character starting from two
// corners
for (int i=0; i<n/2; i++)
{
char tmp = str[i];
str[i] = str[n-i-1];
str[n-i-1] = tmp;
}
}

void replaceAll(string &str, char oldChar, char newChar)
{
int n = str.length();

// Swap character starting from two
// corners
for (int i=0; i<n; i++)
{
if (str[i] == oldChar)
{
str[i] = newChar;
}
}
}

bool startsWith(string str, string start)
{
int lenstr = str.length();
int lenstart = start.length();
if (lenstart == 0 || lenstart > lenstr)
{
return false;
}
  
for(int i = 0; i < lenstart; i++)
{
if (start[i] != str[i])
{
return false;
}
}
return true;
}

bool endsWith (string str, string end)
{
int lenstr = str.length();
int lenend = end.length();
if (lenend == 0 || lenend > lenstr)
{
return false;
}
  
for(int i = lenend-1, j = lenstr-1; i >= 0 ; i--, j--)
{
if (end[i] != str[j])
{
return false;
}
}
return true;
}

// Driver program
int main()
{
string str = "clientstring";
cout << "Original string: " << str << endl;
reverse(str);
cout << "Reversed string: " << str << endl<<endl;

cout << "Original string: " << str << endl;
replaceAll(str, 'i', 'o');
cout << "String after replaceAll i with o: " << str << endl<<endl;

str = "santa monica";
string start = "santa";
if (startsWith(str, start))
{
cout << str << " starts with " << start << endl<<endl;
}

string end = "ica";
if (endsWith(str, end))
{
cout << str << " ends with " << end << endl<<endl;
}

return 0;
}