根据子字符串find删除列表条目

时间:2014-05-02 12:48:21

标签: c substring strstr

我想编写一个函数,如果它在结构中保存的作者名称中找到子字符串,则删除结构列表的条目。问题是,strstr()似乎没有找到任何匹配。我不想知道我是否正确删除条目或以正确的方式移动列表指针(想要自己解决)。

void z(LIBRARY *first){
   int  i = 0, j = 0 ;
   LIBRARY *nextZ = first->next , *prevZ = first;
   char *name = (char*) malloc (102*sizeof(char)), *name2 = (char*) malloc (102*sizeof(char)), c ;

   getchar();

   fgets(name, 102, stdin); // Function gets the string the user is looking for.
   while (name[j]!= '\0'){
     name[j]= toupper(name[j]);  // Converts it to upper case to ignore case types.
     j++;
   }
   j=0;
   printf("%s", name);

   while ( nextZ ){ // Function starts going through the list of structures

     name2 = nextZ->authors; //Function gets string saved in current structure->authors
     while (name2[j]!= '\0'){
        name2[j]= toupper(name2[j]);
        j++;
     }
     j = 0;
     printf("%s", name2);

     if ( (strstr( name2, name))!=NULL ){ 
         /*This is where the problem is. It seems like   
         the function never finds a substring in the structure->authors entry.*/
        i++;
        prevZ->next = nextZ->next;
        nextZ = nextZ->next->next;
     }
     else {
        prevZ = prevZ->next;
        nextZ = nextZ->next;
     }

   }
 printf("Vymazalo sa %d zaznamov\n", i); //Prints out how many entries of the list got deleted.
}

1 个答案:

答案 0 :(得分:0)

我已经设法解决了我遇到的所有问题 - 这就是我为所有感兴趣的人所做的事情:

void z(LIBRARY *first){
 int  i = 0, j = 0 ;
 LIBRARY *nextZ = first->next , *prevZ = first;
 char *name = (char*) malloc (102*sizeof(char)), *name2 = (char*) malloc (102*sizeof(char));

 getchar();  //getting an '\n' that could remain from main when calling z()

 fgets(name, 102, stdin);        //scanning author the user wants to delete
 while (name[j]!= '\0'){
     if (name[j]=='\n') {        //removing end of line character from user input
                 name[j]='\0';
                 break;
     }
     if (name[j]>='a' && name[j]<='z') name[j]= toupper(name[j]);        //chaning user choice to upper case letters for string comparison
     j++;
 }
 j=0;

 while ( nextZ ){    //While cycle that goes through the list of structures

     strcpy(name2, nextZ->authors);  //gets author name from current list entry
     while (name2[j]!= '\0'){

         if (name2[j]>='a' && name2[j]<='z') name2[j]= toupper(name2[j]);    //Once again- change to upper case for string comparison
         j++;
     }
     j = 0;

     if ( (strstr(name2,name))!=NULL ){      //strstr- returns a pointer if match is found- otherwise returns NULL
         i++;
         prevZ->next = nextZ->next; //removes the entries from the list
         nextZ = nextZ->next;

     }
     else { //if strings dont match the list moves to the next entry
         prevZ = prevZ->next; 
         nextZ = nextZ->next;
     }

 }
 printf("%d entries deleted.\n", i); //prints out number of deleted entries
}