I have a 2D array of strings loaded with getline from stdin example :
Hi my name is John.
I like chocolate.
Then i want to search if entered string / substring matches with one of the string arrays example :
Ohn. - matches at line 1
chocolate. - matches at line 2
I'm using standart function strstr :
if ( ( strstr(array[i],string) ) != NULL ) {
printf("Match");
}
The problem is that when i want to find a string which is not at the end of the string like i wrote , it does not match because probably when i want to find "like" in the string it probably compares like\0 with "like" so it will never match.
When i load the line with getline to buffer i used function: strlen(buffer)-1 then i allocated memory for strlen(buffer) - 1 * sizeof(char) and then copied it to the array with memcpy function. Everything worked perfectly but when the string has lenght of 7-8 it puts 2 undefined characters at the end of the string example :
Enter string :testtttt
memcpy to allocated array of strlen(string) - 1
printed string from array looks like : testttttt1� or testtttttqx etc..
Strings with length less then 7 or more than 8 characters work perfectly. If you know how to fix this problem or know a better way to make from string\0 just string without \0 let me know i will be thankful.
Part of the code which does not work. Only matches wtith ending strings like i mentioned.Pole is 2D array of strings, line is buffer where the string is stored.
size_t len = 0;
char *line = NULL;
int number;
while ( (number = getline(&line, &len, stdin ) ) != -1 ) {
for (i = 0; i < index; i++) {
if(strstr(pole[i], line) != NULL) {
printf("Match");
}
}
}
6
John.
'Hi my name is John.
' contain 'John.
'
'Testing stuff
' does not contain 'John.
'
'I do not know what to write
' does not contain 'John.
'
8
Testing
'Hi my name is John.
' does not contain 'Testing
'
'Testing stuff
' does not contain 'Testing
'
'I do not know what to write
' does not contain 'Testing
'
5
know
'Hi my name is John.
' does not contain 'know
'
'Testing stuff
' does not contain 'know
'
'I do not know what to write
' does not contain 'know
'