Home > OS >  Split a string in an array of strings in c
Split a string in an array of strings in c

Time:10-02

I am trying to split a string based on a given char, in this case ' ' and assign each word to an array of strings and print out each element of the array.

So far, I am able to get each word of the string except for the last one :(

How do I get the last word?

code:

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

int main()
{
    char    str[101] = "Hello my name is balou";
    char    temp[101];
    char    arr[10001][101];
    int     count;
    int     i;
    int     j;

    count = 0;
    i = 0;
    j = 0;
    while (str[i] != '\0')
    {
        if (str[i] == ' ' || str[i] == '\n')
        {
            strcpy(arr[count], temp);
            memset(temp, 0, 101);
            count  = 1;
            j = 0;
            i  ;
        }
        temp[j] = str[i];
        i  ;
        j  ;

    }

    i = 0;
    while (i < count)
    {
        printf("arr[i]: %s\n", arr[i]);
        i  ;
    }
    return (0);
}

output:

arr[i]: Hello
arr[i]: my
arr[i]: name
arr[i]: is

CodePudding user response:

Since you do:

while (str[i] != '\0')

you won't do any strcpy of the last word.

You can add

strcpy(arr[count], temp);
count  = 1;

just after the while

But...

Notice that your current code has a number of problems. For instance double spaces, strings ending with a space, strings starting with a space, etc.

Further do

char    temp[101];  -->   char    temp[101] = { 0 };

and also add some code to ensure that j never exceeds 100

and... the size of char arr[10001][101]; may be too big as a variable with automatic storage duration on some systems.

And

printf("arr[i]: %s\n", arr[i]); --> printf("arr[%d]: %s\n", i, arr[i]);

CodePudding user response:

Research string token strtok function and accessing values pointed by array of pointers.
enter image description here

  • Related