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

如何用for/do while循环按长度排序输出字符串所有子串?

How to Output All Substrings Sorted by Length (No Arrays, Only Loops)

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:

  1. First calculate the total length of the input string.
  2. Iterate over substring lengths starting from 1 (shortest) up to the full length of the string (longest).
  3. For each length, generate every possible substring of that length by shifting the starting position across the string.
  4. 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:

  1. Calculate String Length:

    • The while loop 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.
  2. Outer Loop (Substring Length):

    • We start with current_len = 1 (shortest possible substring: single characters) and go up to total_length (the full string itself). This ensures we output substrings in order of increasing length.
  3. 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_len prevents us from going out of bounds.
  4. Inner Loop (Output Substring):

    • This loop prints each character of the substring starting at start_pos for current_len characters. We don't store the substring—we just print it directly, which avoids needing an array.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:17:20