【发布时间】:2021-10-01 11:35:10
【问题描述】:
我正在尝试根据给定的字符拆分字符串,在本例中为' ',并将每个单词分配给字符串数组并打印出数组的每个元素。
到目前为止,除了最后一个之外,我能够获取字符串的每个单词:(
我如何得到最后一个字?
代码:
#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);
}
输出:
arr[i]: Hello
arr[i]: my
arr[i]: name
arr[i]: is
【问题讨论】:
-
至于您的问题,您需要在拆分循环后额外调用
strcpy才能获得最后一部分。 -
memset(temp, 0, 101)也应该在您进入 while 循环之前调用 。顺便说一句,它应该是memset(temp, 0, sizeof(temp)),以防您更改temp的大小。