Search code examples
clinked-list

How to print out the mini strings in a string divided by '.' using linked lists in c


WE are given a string which is "divided" by '.' and we have to use linked lists to print out the parts of the string

My problem are 2

  1. The first is that in the parts im printing there is a wierd type of character which i normally associate with error. Basically something that should not be printed

  2. The last node doesnt print and i cant figure out how to add it

This is my code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node
{
    char *word;
    struct node *next;
}node_t;


node_t *split_string(char *str)
{
    int i=0,j=0;
    int k=0;
    int count=0;
    node_t *head=NULL,
            *tmp=NULL,
            *p=NULL;
    char buffer[20];
    for(i=0;i<strlen(str);i++)
    {
        if(str[i]!='.')
            count++;

        else
        {

            for(j=i-count;j<i;j++)
            {
                buffer[k]=str[j];
                k++;
            }
            k=0;
            count=0;
            tmp=(node_t*)malloc(sizeof(node_t));
            if(tmp == NULL)
            {
                exit(1);
            }
            tmp->next=NULL;
            tmp->word=strdup(buffer);
            if(tmp->word == NULL)
            {
                exit(2);
            }
            if(head == NULL)
            {
                head=tmp;
            }
            else
            {
                p=head;
                while(p->next != NULL) // I know that the problem is here but if i switch   
                                       // it to while(p != NULL) it wont print anything
                {
                    p=p->next;
                }
                p->next=tmp;
            }
        }
    }
    return head;

}
void printList(node_t *head)
{
    node_t *tmp=head;
    int i=1;
    while(tmp != NULL)
    {
        printf("Node %d -> %s\n",i,tmp->word);
        tmp=tmp->next;
        i++;
    }
}
int main()
{
    char str[]={"aaa.sss.ddd.aaa.ddd.ddd"};
    node_t *head=NULL;
    head=split_string(str);
    printList(head);
    return 0;
}

Solution

  • This is because you are only looking for a '.' as the terminator of a node. The last node ends with a null terminator. Try the following:

    for(i=0; i < strlen(str)+1; i++) // allow the loop to include the null termintor
    {
        if(str[i] != '.' && str[i] != 0) // check for end of string as well
            count++;
        else {
            // do you stuff
        }
    }
    

    BTW, the code can be refactored.