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

C语言:不使用strtok从字符串提取单词存入数组(代码求助)

Fixing Your C Word-Splitting Code (No strtok Allowed)

Hey there, let's walk through why your current code isn't working and fix it step by step. Your core goal is totally doable—we just need to straighten out the logic and fix a few critical oversights.

What's Wrong With the Original Code?

Let's break down the key issues:

  • Backwards loop logic: You're using j to iterate through every character in the input string, but you're also trying to use it as the index for your word array. This means you're overwriting random positions in array instead of grouping characters into words.
  • No handling for spaces: When you hit a space, your inner loop stops, but you don't reset your character index or move to the next word slot. You also don't skip over multiple spaces, which would create empty "words".
  • Missing string terminators: C strings require a '\0' at the end to be valid. Your code never adds these, so any attempt to print or use the words later will cause undefined behavior.
  • Unsafe gets() function: This function is deprecated because it doesn't check input length—if someone enters more than 9999 characters, it'll overflow your buffer and crash (or worse).

Fixed Code

Here's a revised version that addresses all these issues, with comments explaining each part:

#include <stdio.h>
#include <ctype.h> // For isspace() to detect all whitespace

int main() {
    char s[10000]; // Store input sentence
    char array[100][100]; // Store up to 100 words, each max 99 chars (plus '\0')
    
    printf("Insert sentence: ");
    
    // Replace unsafe gets() with fgets()
    if (fgets(s, sizeof(s), stdin) == NULL) {
        printf("Error reading input!\n");
        return 1;
    }
    
    // Remove the newline character fgets adds (if present)
    char *newline_ptr = s;
    while (*newline_ptr != '\0') {
        if (*newline_ptr == '\n') {
            *newline_ptr = '\0';
            break;
        }
        newline_ptr++;
    }
    
    int word_count = 0; // Track which word we're storing (array index)
    int char_pos = 0; // Track current character position in the word
    
    for (int i = 0; s[i] != '\0'; i++) {
        // Check if current character is whitespace (space, tab, etc.)
        if (isspace(s[i])) {
            // Only finalize the word if we were actively building one
            if (char_pos != 0) {
                array[word_count][char_pos] = '\0'; // Add string terminator
                word_count++;
                char_pos = 0; // Reset for next word
            }
            continue; // Skip extra spaces
        }
        
        // Make sure we don't overflow the word buffer
        if (char_pos < 99) {
            array[word_count][char_pos] = s[i];
            char_pos++;
        }
    }
    
    // Finalize the last word (in case the sentence doesn't end with a space)
    if (char_pos != 0) {
        array[word_count][char_pos] = '\0';
        word_count++;
    }
    
    // Test print the split words to verify
    printf("\nSplit words:\n");
    for (int k = 0; k < word_count; k++) {
        printf("Word %d: %s\n", k+1, array[k]);
    }
    
    return 0;
}

Key Improvements Explained

  • Safe input handling: fgets() ensures we don't overflow the input buffer, and we clean up the newline character it includes.
  • Clear word tracking: word_count keeps track of which index in array we're using, while char_pos tracks where we are in the current word.
  • Whitespace handling: isspace() catches all whitespace characters (not just spaces), and we skip consecutive spaces to avoid empty words.
  • Buffer safety: We cap each word at 99 characters to prevent overflowing the array's second dimension.
  • Valid C strings: Every word gets a '\0' terminator, so they work with standard string functions like printf().

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:02:43