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
jto 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 inarrayinstead 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_countkeeps track of which index inarraywe're using, whilechar_postracks 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 likeprintf().
内容的提问来源于stack exchange,提问作者user9542624
相关产品推荐
相关产品推荐

