Reputation: 322
I have a program in C which stores a list of students working with linked lists as college project.
typedef struct
{
int day;
int month;
int year;
} date_t;
typedef struct
{
char name[50];
int dni;
char email[30];
float mark;
date_t birthDate;
bool gender;
} student_t;
typedef struct node
{
student_t student;
struct node *next;
} node_t;
int main() {
node_t *list;
InitList(&list);
ReadFromFile(&list);
//SearchByDni(list, 34790767);
//PrintList(list);
SearchByName(list, "mari");
printf("\nListSize: %u\n", ListSize(list));
printf("");
return 0;
}
I fill the list from a file with students(this part works ok), but once i have the list filled, i need a method to search in the students list by a given name(char[])
void SearchByName(node_t *list, char *name){
node_t *p;
int len;
int nameLength = strlen(name);
int studentsCount = 0;
for (p = list; p != NULL; p = p->next) {
len = strspn(p->student.name, name);
if (nameLength == len) {
studentsCount++;
printf("%s", p->student.name);
}
}
printf("Students found searching '%s': %d\n", name, studentsCount);
}
The function works fine, i am using a string.h function called strspn . As the definition of the function says, it returns the length of the substring2 found in string1, so once i get the length i compare it with the length of the substring given as a parameter to do the search in the list, if they are the same it means i found one of the results of the search. This works fine, but i just came across when this substring is "Mari" it does not work properly.
This is what the file where i get the data looks like. If i search with the substring "mari" i should print in the screen that i found 2 results, maria and mariano, because both match. And this is what i get:
Although now if we change the parameter from "mari" to "mar":
The function strspn works fine in all the cases i tried unless with mari and i have no idea why.
You can test in this example that it returns length 5 insted of 4 that is the correct one.
And if you try the same code changing "mari" to "mar" it returns 3 which is the correct length that matches:
If anyone knows how to solve this.
Upvotes: 1
Views: 372
Reputation: 182763
Five is the correct answer, There are five consecutive characters in "maria" that are also in "mari" -- "m", "a", "r", "i", and "a". The strspn
function gives you the number of consecutive characters in the first string, starting from the beginning, that are also in the second string. Since "a" is in the second string, it always counts.
Upvotes: 1