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

C语言单词内字符去重问题:代码运行无输出求助

你的C语言字符串去重问题分析与修复

代码中的核心问题

  • notalphabet函数逻辑颠倒:你需要收集字母组成单词,但原函数的判断逻辑导致代码只会收集非字母字符,完全跳过了单词内容,这是无输出的根本原因。
  • isduplicate指针类型错误:strchr返回char*类型,你错误地赋值给int*变量,会导致内存访问异常。
  • eliminate函数的j传值无效:传值调用下,函数内修改的j不会同步到外部的j,最终res的索引始终停留在0,最后被设为'\0'导致无输出。
  • main函数循环逻辑混乱:处理完单词后的索引操作错误,会跳过字符或访问越界;未正确处理单词间的空格;token未初始化,存在垃圾值干扰判断。
  • gets函数不安全:该函数已被C标准废弃,容易造成缓冲区溢出。

修正后的代码

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

bool isduplicate(char ch, char str[]);
int eliminate(char res[], char token[], int j, int tok);
bool isalphabet(char ch);

// 判断字符是否已存在于结果字符串中
bool isduplicate(char ch, char str[])
{
    char* res = strchr(str, ch);
    return res != NULL;
}

// 判断是否为小写字母
bool isalphabet(char ch)
{
    return (ch >= 'a' && ch <= 'z');
}

// 处理单个单词的去重,返回更新后的结果索引
int eliminate(char res[], char token[], int j, int tok)
{
    for (int i = 0; i < tok; i++)
    {
        if (!isduplicate(token[i], res))
        {
            res[j] = token[i];
            j++;
        }
    }
    return j;
}

int main()
{
    int j = 0;
    char str[100], res[100] = {0}; // 初始化res避免垃圾值
    int i = 0;

    printf("Enter a string:\n");
    // 用fgets替代gets,去除换行符
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    while (str[i] != '\0')
    {
        char token[100] = {0}; // 初始化token
        int tok = 0;

        // 收集当前单词的所有字母
        while (str[i] != '\0' && isalphabet(str[i]))
        {
            token[tok] = str[i];
            i++;
            tok++;
        }

        // 处理当前单词去重,更新结果索引
        if (tok > 0)
        {
            j = eliminate(res, token, j, tok);
        }

        // 处理单词间的空格(保留一个空格)
        if (str[i] == ' ' && str[i+1] != '\0')
        {
            res[j] = ' ';
            j++;
            i++;
            // 跳过连续空格
            while (str[i] == ' ')
            {
                i++;
            }
        }
        else if (str[i] != '\0')
        {
            i++;
        }
    }

    res[j] = '\0';
    printf("The resulting string is: %s\n", res);
    return 0;
}

关键修改说明

  1. 重命名并修正了字母判断函数为isalphabet,逻辑更清晰,确保正确收集单词字符。
  2. 修复isduplicate的指针类型错误,正确使用char*接收strchr的返回值。
  3. 修改eliminate函数为返回更新后的索引j,确保结果字符串的索引正确推进。
  4. 初始化res和token数组,避免垃圾值干扰判断。
  5. 用fgets替代gets,并处理换行符,提升安全性。
  6. 重构main函数的循环逻辑,正确处理单词收集、去重、空格保留,避免索引越界和字符跳过。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 09:02:45