You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言分割字符串为字符串数组时丢失最后一个单词如何解决

问题根因

你的代码仅在遍历到空格、换行符时才会将临时存储的单词存入结果数组,但是原字符串最后一个单词的末尾是字符串结束符\0,没有匹配到触发存储的条件,所以最后一个单词一直留在临时数组temp里没有被存入结果数组arr,同时计数变量count也没有统计到最后一个单词,自然打印的时候不会输出。
另外你现有逻辑还有一个隐藏问题:如果原字符串首尾存在多余空格、或者连续出现多个空格,会拆分出空字符串存入数组,可以根据实际需求额外加个非空判断过滤。

调整方案

只需要在遍历字符串的while循环结束后,主动把temp里存储的最后一个单词存入arr,并给计数变量count加1即可,修改后的完整代码如下:

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

int main()
{
    char    str[101] = "Hello my name is balou";
    char    temp[101] = {0}; // 初始化temp避免脏数据
    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')
        {
            // 可选:加非空判断过滤连续空格、首尾空格产生的空字符串
            if (j > 0) {
                strcpy(arr[count], temp);
                memset(temp, 0, 101);
                count += 1;
                j = 0;
            }
            i++;
        }
        temp[j] = str[i];
        i++;
        j++;

    }
    // 新增:存储最后一个单词
    if (j > 0) {
        strcpy(arr[count], temp);
        count += 1;
    }

    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
arr[i]: balou

内容的提问来源于stack exchange,提问作者Balou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:45:04