Java字符串左缩进格式化函数:超长单词换行填充问题求助
Got it, let's work through this problem. Your current code handles indentation and redundant spaces well, but it misses the critical logic for wrapping long words—specifically, padding the current line to the limit before breaking when a word can't fit, then starting the word on a new line. And since you can only use charAt() and length(), we'll build this logic manually without any helper methods like split().
Key Issues in the Current Code
The existing logic splits lines strictly when charCount hits the limit, regardless of whether we're in the middle of a word. This means long words get chopped mid-way, and we never pad the line to the full limit before breaking for the word.
Step-by-Step Solution
We'll adjust the traversal logic to:
- Detect upcoming word length: When we're running out of space in the current line, check how long the current word is (from the current character to the next space or end of string).
- Pad and break if needed: If the word can't fit in the remaining space, fill the current line with spaces to reach the limit, add the closing
], start a new line with[, and then add the word to the new line. - Maintain existing functionality: Keep the redundant space removal and line indentation (the
[/]wrapping) intact.
Modified Code
Here's the updated implementation that meets all your requirements:
void runApp(){ String text = " Knowing You Jesus " + " Graham Kendrick " + "All I once held dear, built my life upon " + "All this world reveres, and wars to own " + "All I once thought gain I have counted loss " + "Spent and worthless now, compared to this " + "Knowing you, Jesus " + "Knowing you, there is no greater thing " + "You're my all, you're the best " + "You're my joy, my righteousness " + "And I love you, Lord " + "Now my heart's desire is to know you more " + "To be found in you and known as yours " + "To possess by faith what I could not earn " + "All-surpassing gift of righteousness " + "Oh, to know the power of your risen life " + "And to know You in Your sufferings " + "To become like you in your death, my Lord " + "So with you to live and never die " + "Source: Musixmatch " + "Songwriters: Tim Hughes / Ben Cantelon "; int limit = 60; System.out.println(" 123456789012345678901234567890123456789012345678901234567890"); System.out.println(leftTextFormat(text, limit)); System.out.println(); } String leftTextFormat(String text, int limit){ String formattedText = "["; int charCount = 0; int textLength = text.length(); // First, skip leading spaces int i = 0; while (i < textLength && text.charAt(i) == ' ') { i++; } while (i < textLength) { char currentChar = text.charAt(i); // Handle redundant spaces: only add if previous character isn't a space if (currentChar == ' ') { if (formattedText.charAt(formattedText.length() - 1) != ' ') { formattedText += currentChar; charCount++; } i++; continue; } // Calculate the length of the current word (from i to next space or end) int wordLength = 0; int temp = i; while (temp < textLength && text.charAt(temp) != ' ') { wordLength++; temp++; } // Check if the current word can fit in the remaining space of the line int remainingSpace = limit - charCount; if (wordLength > remainingSpace && charCount != 0) { // Pad the current line to the limit with spaces while (charCount < limit) { formattedText += ' '; charCount++; } // Close the line and start a new one formattedText += "]\n["; charCount = 0; } // Add the current character to the formatted text formattedText += currentChar; charCount++; i++; // Check if we've reached the line limit (and not at start of line) if (charCount == limit && i < textLength) { formattedText += "]\n["; charCount = 0; } } // Add closing bracket for the last line, pad if needed while (charCount < limit) { formattedText += ' '; charCount++; } formattedText += "]"; return formattedText; }
Explanation of Key Changes
- Leading Space Skip: We first skip any leading spaces in the input text to avoid starting with an empty line.
- Word Length Calculation: For each non-space character, we calculate how long the current word is by traversing until the next space or end of string. This lets us check if it can fit in the remaining line space.
- Line Padding & Breaking: If the word can't fit, we fill the current line with spaces to hit the
limit, close the line, start a new one, and then add the word to the new line. - Final Line Padding: After processing all characters, we pad the last line to the full limit to ensure consistency.
Expected Output
When you run this, lines that would have chopped a long word will instead be padded to 60 characters, then the long word starts on a new line. For example, the word "All-surpassing" will trigger this logic if it can't fit in the remaining space of a line.
内容的提问来源于stack exchange,提问作者YHStan

