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

1 THE MYSTRCHR FUNCTION Write the function myStrChr(). The function has two para

ID: 3713980 • Letter: 1

Question

1 THE MYSTRCHR FUNCTION
Write the function myStrChr(). The function has two parameters: a const char * s pointing to
the first character in a C-style string, and a char c. Return a pointer to the first appearance of c
appearing inside s and nullptr (0) if c does not appear inside s.

Here is the support file, keep in mind we are doing C-string strings and pointers.

/**

CS 150 C-Strings

Follow the instructions on your handout to complete the

requested function. You may not use ANY library functions

or include any headers, except for <cstddef> for size_t.

*/

#include <cstddef> // size_t for sizes and indexes

///////////////// WRITE YOUR FUNCTION BELOW THIS LINE ///////////////////////

// function here

///////////////// WRITE YOUR FUNCTION ABOVE THIS LINE ///////////////////////

// These are OK after the function

#include <iostream>

#include <string>

using namespace std;

void CHECK(const char*, char, const string&);

void studentTests()

{

cout << "Student testing. Add code in this function." << endl;

cout << "-------------------------------------------------------------" << endl;

CHECK("Aardvark", 'a', "ardvark");

CHECK("Aardvark", 'k', "k");

CHECK("Aardvark", 'A', "Aardvark");

CHECK("Aardvark", 'K', "nullptr");

cout << endl;

cout << "--done--" << endl;

}

int main()

{

studentTests();

}

#include <cstring>

void CHECK(const char * s, char c, const string& expected)

{

char data[1024];

strcpy(data, s);

string msg = "myStrChr("" + string(data) + "", '" + c + "')";

auto p = myStrChr(data, c);

string actual = (p ? string(p) : "nullptr");

if (expected == actual)

cout << " + " + msg + "->OK" << endl;

else

cout << " X " + msg + " expected<"" + expected + "">, found <"" + actual + "">" << endl;

}

Explanation / Answer

Hi Dear,

Please find my implementation.

char* myStrChr(const char * s, char c)
{
   int i, len;

   len = strlen(s);

   for(i=0; i<len; i++)
   {
       if(s[i] == c)
       {
           return (s+i);
       }
   }

   return NULL;
}