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

strcpycall after the splitting loop to get the last part.memset(temp, 0, 101)should also be called before you enter the while loop. And BTW it should bememset(temp, 0, sizeof(temp)), in case you change the size oftemp.