4 THE FINDANY FUNCTION Write the function findAny().The function has two paramet
ID: 3716893 • Letter: 4
Question
4 THE FINDANY FUNCTION
Write the function findAny().The function has two parameters: a const char * s pointing to the
first character in a C-style string, and a const char * letters. Return the index of the first
character in s that matches any letter inside letters. Return -1 if no letters match.
Here is the support file that will be used test code, we are currently working with pointers and C-style strings. Thank you
/**
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 goes here
///////////////// WRITE YOUR FUNCTION ABOVE THIS LINE ///////////////////////
// These are OK after the function
#include <iostream>
#include <string>
using namespace std;
void CHECK(const char*, const char *, int);
void studentTests()
{
cout << "Student testing. Add code in this function." << endl;
cout << "-------------------------------------------------------------" << endl;
CHECK("This is a test.", "!.,?;:", 14);
CHECK("This is a test.", "sth", 1);
CHECK("This is a test.", "aeiou", 2);
CHECK("This is a test.", " ", 4);
CHECK("This is a test.", "Bob", -1);
cout << endl;
cout << "--done--" << endl;
}
int main()
{
studentTests();
}
#include <cstring>
string repl(const string& s)
{
string r;
for (auto c: s)
{
switch(c)
{
case ' ': r += R"( )"; break;
case ' ': r += R"( )"; break;
case ' ': r += R"( )"; break;
default: r += c;
}
}
return r;
}
void CHECK(const char * s1, const char * s2, int expected)
{
string msg = "findAny("" + string(s1) + "", "" + repl(string(s2)) + "")";
char d1[1024], d2[1024];
strcpy(d1, s1);
strcpy(d2, s2);
int actual = findAny(d1, d2);
if (expected == actual)
cout << " + " + msg + "->OK" << endl;
else
cout << " X " + msg + " expected<" << expected << ">, found <" << actual << ">" << endl;
}
Explanation / Answer
Please find my implementation of required method.
findAny function:
int findAny(const char* s, const char* letters)
{
int i, j, len1 = strlen(s), len2 = strlen(letters);
for (i = 0; i < len1; i++) {
for (j = 0; j < len2; j++) {
if (s[i] == letters[j]) {
return i;
}
}
}
return -1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.