Search code examples
carraysstringargvargc

How to split a string into words?


I am trying to split strings into words. Can anyone help me on how to implement it without using strtok and another function other than main?

void main()
{
    int i;
    int myargc = 1;
    char *myargv[256];
    char buff[100];
    int len = 0;
    char string[256];
    int j = 0;

    printf("Enter text: ");
    gets(buff);

    for(i = 0; buff[i] != '\0'; i++){
        len++;
    }

    for(i = 0; i < len; i++)
    {
        if(buff[i]!=' ' && buff[i+1]==' ')
        {
            myargc++;
        }
    }
    printf("myargc %d\n",myargc);

    **for(i = 0; i < len; i++){
        if(buff[i] != ' '){
            string[j++] = buff[i];
        }
        if(buff[i] != ' ' && buff[i] == ' '){
            string[j++] = '\0';
            j = 0;
        }
        if(buff[i] == '\0'){
            break;
        }
    }**
    for(i = 0; i < myargc - 1; i++){
        myargv[i] = string;
        printf("argv[%d]\t%s\n", i, myargv[i]);
    }
}

When I entered "a b c" for example, my output looked like this:

myargc 3
argv[0] abc
argv[1] abc
argv[2] abc

Solution

  • So here is my solution, not sure if it is optimal, but works also with more spaces between words.

    #include <stdio.h>
    #include <stdlib.h>
    
    void main()
    {
        int i;
        int myargc = 1;
        char **myargv;
        char buff[100];
        int len = 0;
        char string[256];
        int j = 0, k =0;
    
        printf("Enter text: ");
        gets(buff);
    
        for(i = 0; buff[i] != '\0'; i++){
            len++;
        }
    
        for(i = 0; i < len; i++)
        {
            if(buff[i]!=' ' && buff[i+1]==' ')
            {
                myargc++;
            }
        }
        printf("myargc %d\n",myargc);
    
        //allocating 256 bytes * number of words    
        myargv = (char**)malloc(myargc*sizeof(char*));
        for(i = 0; i < myargc; i++){
            myargv[i] = (char*)malloc(256*sizeof(char));
        }
    
        //iterating until the ending character
        for(i = 0; i <= len; i++){
            //building word
            if(buff[i] != ' ' && buff[i] != 0)
            {   
                string[j++] = buff[i];
            }
    
            //copying word to corresponding array
            else if((buff[i] == ' ' && buff[i+1] != ' ') || (buff[i] == 0))
            {
                for(int z = 0; z < j; z++){
                    myargv[k][z] = string[z];
                }
    
                myargv[k++][j] = '\0';
                j = 0;
            }
    
            //skipping more spaces in a row
            else continue;
        }
    
    
        for(i = 0; i < myargc; i++){
            printf("argv[%d]\t%s\n", i, myargv[i]);
        }
    
        }