Answer to Question #267538 in C++ for malika

Question #267538
  1. Rewrite the following function so that it does not use any square brackets (not even in the parameter declarations) but does use the integer variable k. Do not use any of the <cstring> functions such as strlen, strcpy, etc.
    // This function searches through str for the character chr.
    // If the chr is found, it returns a pointer into str where
    // the character was first found, otherwise nullptr (not found).

    const char* findTheChar(const char str[], char chr)
    {
        for (int k = 0; str[k] != 0; k++)
            if (str[k] == chr)
                return &str[k];

        return nullptr;
    }
  1. Now rewrite the function shown in the previous so that it uses neither square brackets nor any integer variables. Your new function must not use any local variables other than the parameters. Do not use any of the <cstring> functions such as strlen, strcpy, etc.
1
Expert's answer
2021-11-19T17:16:26-0500

1..

const char* findTheChar(const string &str,char chr)
    {
        for (int k = 0; str.length(); k++)
            if (str[k] == chr)
                return &str[k];
        return nullptr;
    }


2..

const char* findTheChar(const string &str,char chr)
    {
        for (auto &ch : str) {
            if (ch == chr)
                return &ch;
        }
        return nullptr;
    }

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS