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
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]);
Research string token strtok
function and accessing values pointed by array of pointers.
strtok()
array of pointers
#include <string.h>
#include <stdio.h>
int main ()
{
char str[80] = "Hello my name is balou";
const char s[2] = " "; //delimiter
char *token;
char *words[5]; //store words
int i = 0;
/* get the first token */
token = strtok(str, s);
/* walk through other tokens */
while( token != NULL )
{
words[i++] = token;
token = strtok(NULL, s);
}
int r, c;
// print words
for (r = 0; r < 5; r++)
{
c = 0;
while(*(words[r] + c) != '\0')
{
printf("%c", *(words[r] + c));
c++;
}
printf("\n");
}
return(0);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.