I should have been more explicit in my question. Ill clarify it more by using the actual example that's bothering me. Suppose I want to search a word in a paragraph (example)....
So the paragraph (with new line characters) is loaded as an array of characters.
Now I prompt the user to search any word in that paragraph. This word is also an array called char search [x]. Note the 'x' that im using for now. thats the issue im having. The size of that array depends on what the user types. It could be "John" or "because", i.e. variable size character arrays.
Now you may immediately say, why not just use a size 100 array and the user fills in whatever number under 100 and you simply add a '\0' termination. But unfortunately it simply doesnt work.
the text file (an array) and search word (array) are declared:
char text[36000],search_word[11];
The search function called strindex is written:
1 2 3 4 5 6 7 8 9 10 11
|
int strindex(char s[], char t[])
{
int i, j, k;
for (i = 0; s[i] != '\0'; i++) {
for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++)
;
if (k > 0 && t[k] == '\0')
return i;
}
return -1;
}
|
Note that it returns the position in the array that the start of the search word character is in. Also note that it returns -1 upon error.
Now to prompt the user for an input (asking for the search word):
1 2 3 4 5 6
|
for(j=0;j<=10/*c!='\n'*/;j++)
{
c=getchar();
search_word[j]=c;//getchar
}
|
So what is the problem im having? The following:
If my search word is exactly 11 characters long (As declared in the first code I posted) then it will find that array position in the file. So thats good. However, that search word must be 11 characters long. I cant put any other search word other than 11 characters. You may reply saying why not try?:
1 2 3 4 5 6 7
|
for(j=0;j<=10/*c!='\n'*/;j++)
{
c=getchar();
search_word[j]=c;//getchar
if(search_word[j]=='\n')
search_word[j]=='\0';
}
|
Yes it does terminate it under 11 characters but when its passed to strindex (the search function) it returns an error (-1), in other words, it didnt find that search word.
I may know what the problem is but I dont have a solution.
Am I right in saying that because I terminated it with a '\0' character, that '\0' is itself part of the search word and thats why it cannot find the search word. Because in the file/paragraph/text, the only '\0' is at the very end of the array. How do I overcome this?