如何用for/do while循环按长度排序输出字符串所有子串?
Hey there! Let's break this down step by step since you're a new programmer—no fancy tricks, just straightforward loops that fit your requirements. The key insight here is we don't need to collect all substrings first and then sort them. Instead, we can generate substrings from shortest to longest directly, which means we never need to store them in an array.
Core Logic
Instead of generating all substrings randomly and sorting later, we:
- First calculate the total length of the input string.
- Iterate over substring lengths starting from 1 (shortest) up to the full length of the string (longest).
- For each length, generate every possible substring of that length by shifting the starting position across the string.
- Output each substring immediately as we generate it—no storage needed!
Example Code (C Language)
This uses only for loops and no arrays to store substrings. We'll use "funny" as the input string:
#include <stdio.h> int main() { // Your input string char input_str[] = "funny"; int total_length = 0; // Step 1: Calculate the total length of the string (no strlen() needed) while (input_str[total_length] != '\0') { total_length++; } // Step 2: Loop through substring lengths from 1 to full string length for (int current_len = 1; current_len <= total_length; current_len++) { // Step 3: Loop through all valid starting positions for this length // Start can go up to (total_length - current_len) to avoid overflow for (int start_pos = 0; start_pos <= total_length - current_len; start_pos++) { // Step 4: Output the substring character by character for (int char_idx = 0; char_idx < current_len; char_idx++) { printf("%c", input_str[start_pos + char_idx]); } printf(" "); // Separate substrings with a space } printf("\n"); // New line after all substrings of this length } return 0; }
Detailed Explanation
Let's walk through each part so you understand exactly what's happening:
Calculate String Length:
- The
whileloop counts each character until it hits the null terminator (\0), which marks the end of the string. This gives us the total number of characters we're working with.
- The
Outer Loop (Substring Length):
- We start with
current_len = 1(shortest possible substring: single characters) and go up tototal_length(the full string itself). This ensures we output substrings in order of increasing length.
- We start with
Middle Loop (Starting Position):
- For each length, we need to find all valid starting positions. For example, if the string is 5 characters long and we want substrings of length 2, the starting position can be 0, 1, 2, or 3 (since 3 + 2 = 5, which is exactly the end of the string). The condition
start_pos <= total_length - current_lenprevents us from going out of bounds.
- For each length, we need to find all valid starting positions. For example, if the string is 5 characters long and we want substrings of length 2, the starting position can be 0, 1, 2, or 3 (since 3 + 2 = 5, which is exactly the end of the string). The condition
Inner Loop (Output Substring):
- This loop prints each character of the substring starting at
start_posforcurrent_lencharacters. We don't store the substring—we just print it directly, which avoids needing an array.
- This loop prints each character of the substring starting at
Output for "funny"
When you run the code, you'll get this sorted output:
f u n n y fu un nn ny fun unn nny funn unny funny
Alternative: Using do-while Loops
If you prefer or need to use do-while instead of for loops, here's how you can rewrite the middle and inner loops:
// Replace the middle and inner for loops with do-while for (int current_len = 1; current_len <= total_length; current_len++) { int start_pos = 0; do { int char_idx = 0; do { printf("%c", input_str[start_pos + char_idx]); char_idx++; } while (char_idx < current_len); printf(" "); start_pos++; } while (start_pos <= total_length - current_len); printf("\n"); }
This works exactly the same way—just uses different loop syntax, which fits your requirement of only using for or do-while loops.
内容的提问来源于stack exchange,提问作者Ata Atasoy

