104k views
5 votes
Write the following function without using the C++ string class or any functions in the standard library, including strlen(). You may use pointers, pointer arithmetic or array notation.Write the function firstOfAny().The function has two parameters (str1, str2), both pointers to the first character in a C-style string.You should be able to use literals for each argument.The function searches through str1, trying to find a match for any character inside str2.Return a pointer to the first character in str1 where this occurs.

User Davlog
by
5.1k points

1 Answer

6 votes

Answer:

The function in C++ is as follows

int chkInd(string str1, string str2){

int lenstr1=0;

while(str1[lenstr1] != '\0'){ lenstr1++; }

int index = 0; int retIndex=0;

for(int i=lenstr1-1;i>=0; i--){

while (str2[index] != '\0'){

if (str1[i] == str2[index]){

retIndex=1;

break; }

else{ retIndex=0; }

index++; }

if (retIndex == 0){ return i; }else{return -1;}}

}

Step-by-step explanation:

This defines the function

int chkInd(string str1, string str2){

First, the length of str1 is initialized to 0

int lenstr1=0;

The following loop then calculates the length of str1

while(str1[lenstr1] != '\0'){ lenstr1++; }

This initializes the current index and the returned index to 0

int index = 0; int retIndex=0;

This iterates through str1

for(int i=lenstr1-1;i>=0; i--){

This loop is repeated while there are characters in str2

while (str2[index] != '\0'){

If current element of str2 and str1 are the same

if (str1[i] == str2[index]){

Set the returned index to 1

retIndex=1;

Then exit the loop

break; }

If otherwise, set the returned index to 0

else{ retIndex=0; }

Increase index by 1

index++; }

This returns the calculated returned index; if no matching is found, it returns -1

if (retIndex == 0){ return i; }else{return -1;}}

}

User GetFuzzy
by
4.5k points