Alrite, I need to search for a word given by a user, my problem is how do you
go about searching the whole array to find the particular word.
P.S - using text files and have initialised the characters into an array of size 1000.
Okay, so, you are giving us an array of characters and a word. What exactly do you want? Do you want the index of the first character of the first instance of the word in the array? What should the function return if no match is found? Be more specific.
Im really sorry,
And yes I want the index of the character that is being searched for, and tell the user that it exists if it doesn't exist just cout a statement that says, it doesn't exist.. The search should start form the beginning of the sentence and go through each letter, searching whether its the same with the given word or not. The sentence is just one line.
int find(char sentence[], std::string word)
{
int j = 0;
for (int i = 0; sentence[i]; i++)
{
if (sentence[i] == word[j])
j++;
else
j = 0;
if (j == word.length())
return i - j + 1;
}
return -1;
}
You need to pass it a null-terminated character array and a string. It returns the index of the first character of the first instance of the string in the array. If there is no match, it returns -1.