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

如何删除数组中的特定单词?及从TXT文件移除长度超5字符的单词

How to Remove Words Longer Than 5 Characters from a Text File in C

Hey there! Let's work through this problem together. First, let's fix a small oversight in your existing code—you're calling fgets() but not properly acting on its return value (right now that line just does a comparison without handling errors). Then we'll add the logic to filter out those long words.

Step 1: Fix File Reading & Add Filtering Logic

We'll split the input string into individual words using strtok(), check each word's length with strlen(), and build a new string containing only words that are 5 characters or shorter. Here's the complete, commented code that works for both single-line and multi-line files:

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

int main() {
    FILE *fp;
    char filtered_str[2500] = {0}; // Initialize to empty to avoid garbage data
    char line[2500];
    char *token;

    // Open the input file
    fp = fopen("a.txt", "r");
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }

    // Read file line by line (handles multi-line content)
    while (fgets(line, 2500, fp) != NULL) {
        // Split the line into words (delimiters: space, newline, tab)
        token = strtok(line, " \n\t");
        
        while (token != NULL) {
            // Keep only words with length ≤ 5
            if (strlen(token) <= 5) {
                // Append the valid word to the filtered string, plus a space
                strcat(filtered_str, token);
                strcat(filtered_str, " ");
            }
            // Grab the next word in the line
            token = strtok(NULL, " \n\t");
        }
    }

    fclose(fp);

    // Optional: Print filtered content to the console
    printf("Filtered content:\n%s\n", filtered_str);

    // Optional: Write filtered content to a new file (safe to avoid overwriting original)
    FILE *fp_out = fopen("filtered_a.txt", "w");
    if (fp_out == NULL) {
        perror("Error opening output file");
        return -1;
    }
    fputs(filtered_str, fp_out);
    fclose(fp_out);

    return 0;
}

Key Details to Keep in Mind:

  • strtok() Behavior: This function automatically skips consecutive delimiters (like multiple spaces), so your filtered output won't have extra blank spaces.
  • String Initialization: Initializing filtered_str to {0} ensures it starts as an empty string, preventing random garbage data from being included.
  • Multi-Line Support: The outer while(fgets(...)) loop reads each line of the file one by one, so it works even if your a.txt has multiple lines of text.
  • Overwriting the Original File: If you want to replace the original a.txt instead of writing to a new file, just change the output filename to "a.txt"—make sure you've already read the original content first!

Quick Adjustments if Needed:

  • If you want to exclude words that are exactly 5 characters long, change strlen(token) <= 5 to strlen(token) < 5.
  • If your file has very long lines, increase the size of the line and filtered_str arrays (just make sure they're large enough for your use case).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:32:45