Create a function called findWord that will return the index of the first charac
ID: 3588563 • Letter: C
Question
Create a function called findWord that will return the index of the first character of a specified word in a CString. Your function should take as parameters the CString to search through and a CString that represents the word to search for. The function will return the index of the first character of the string if it is found. The function should return -1 if the word is not in the string.
NOTE:
You must use pointers to find the word. This means the use of array notation is not allowed
You are not allowed to use function like strstr or strchr to solve this problem. You are to write this algorithm yourself using pointers.
To simplify the algorithm this is a case sensitive search. This means upper and lower case characters should be treated as different characters.
Explanation / Answer
#include<iostream>
#include<cstring>
using namespace std;
int findWord(char *input, const char *find)
{
do
{
const char *p, *q;
int index;
//Checking if substring available in string or not.
for (p = input, q = find,index=0; *q != '' && *p == *q; p++, q++) {
index++;
}
if (*q == '')
{
return index;
}
} while (*(input++) != '');
return -1;
}
// type casting const char* into char *
int findWord(const char *input, const char *find)
{
return findWord(const_cast<char *>(input), find);
}
int main(){
string input,find;
getline(cin,input);
getline(cin,find);
// converting string to const char*
const char* i = input.c_str();
const char* f = find.c_str();
cout << findWord(i,f) <<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.