[英]How to format a String with spaces based on a specified length?
嘗試用Java創建方法通過基於長度擴展緩沖區的內容(通過放置適當數量的空格)來格式化字符串。 因此,基於給定的特定長度,字符串的第一個字符位於第一個索引中,而最后一個字符位於實際的最后一個索引本身。
public static String format(String sentence, int length) {
if (sentence.length() >= length) {
return sentence;
}
StringBuilder sb = new StringBuilder();
String[] words = sentence.split("\\s+");
int usedCharacters = 0;
for (String word : words) {
usedCharacters += word.length();
}
int emptyCharacters = length - usedCharacters;
int spaces = emptyCharacters / words.length - 1;
for (String word : words) {
sb.append(word);
for (int i = 0; i <= spaces; i++) {
sb.append(" ");
}
}
return sb.toString();
}
對於此單元測試,它可以:
@Test
public void isCorrectLength() {
String value = StringUtils.format("brown clown", 20);
assert(value.length() == 20);
}
因此,此處的最大緩沖區大小為:20
使用的字符總數為:10
未使用的字符總數為:10
最終結果(如果打印字符串)為:
brown clown
小丑中的“ n”在索引20處。
但是,在進行以下測試時會出現邊緣情況(這會導致其破裂):
@Test
public void isCorrectLengthWithLongerSentence() {
String value = StringUtils.format("Love programming Java using Eclipse!", 50);
assert(value.length() == 50);
}
緩沖區大小:50
已使用的字符總數:25未使用的字符總數:25
空間:3
最終長度:48
最終結果(如果打印字符串)為:
Love programming Java using Eclipse!
為什么最終指數是48,而不是50?
感嘆號“!” 在“ Eclipse”之后,應該是50,而不是48 ...
我懷疑這是由於我的空間計算被關閉了。
感謝您抽時間閱讀。
對於這個測試
@Test
public void isCorrectLength() {
String value = StringUtils.format("Went to the slope and snowboarded for hours., 103);
assert(value.length() == 103);
}
發生這種情況是因為您正在划分:
int spaces = emptyCharacters / words.length - 1;
這導致(66/8)-1)= 7.25,然后您有了一個for循環,該循環沒有考慮額外的.25,這意味着您將無法填充所需的緩沖區長度。
另外,由於您將其聲明為int,因此不會獲得額外的0.25,因此應將其更改為double
,並將其他類型也強制轉換為double。
然后,您可以對單詞進行計數,並檢查額外的0.25乘以計數器的計數是否達到1,添加空格並重置計數器。
double spaces = (double)emptyCharacters / (double)words.length - 1.0;
double extraSpace = spaces % 1;
double counter = 0;
for (String word : words) {
counter++;
sb.append(word);
for (int i = 0; i <= spaces; i++) {
sb.append(" ");
}
if ((counter * extraSpace) >= 1) {
sb.append(" "); // This is the extra space.
counter = 0;
}
}
這樣的事情。 問題在於並非所有單詞都可以具有相同數量的空格。 為了適應靜態緩沖區的長度,有些會有更多,有些會有更少。 這也是一種特殊情況,因為余數為0.25,並且將恰好產生2個空格,因此您仍然需要容納余數。 (如果它沒有達到1,並且您還有一個字。)
以下代碼彌補了這一點。
double spaces = (double)emptyCharacters / (double)words.length - 1.0;
double extraSpace = spaces % 1;
double counter = 0;
int wordIndex = 0;
for (String word : words) {
counter++;
wordIndex++;
sb.append(word);
for (int i = 0; i <= spaces; i++) {
sb.append(" ");
}
if ((counter * extraSpace) >= 1) {
sb.append(" "); // This is the extra space.
counter = 0;
}
if ((wordIndex == words.length - 1) && (counter * extraSpace) > 0) {
sb.append(" "); // This accounts for remainder.
}
}
無論如何,這都不是很優雅,但是它可以用於先前的測試,例如,對於新的測試:
@Test
public void isCorrectLength() {
String value = StringUtils.format("We went to the giant slope and snowboarded for hours., 103);
assert(value.length() == 103);
}
通過放置單詞,空格,單詞等來重新組合句子。
私有靜態String formatString(String string,int length){//用空格解析單詞String [] words = statement.split(“ \\ s +”);
// calc the char length of all words int wordsLength = 0; for (String w: words) { wordsLength += w.length(); } // find the number of space blocks and initialize them int spacesLength = length - wordsLength; String[] spaceBlocks = new String[words.length - 1]; Arrays.fill(spaceBlocks, ""); // distribute spaces as evenly as possible between space blocks int spacesLeft = spacesLength; int k = 0; while (spacesLeft > 0) { spaceBlocks[k++] += " "; if (k == spaceBlocks.length) { k = 0; } spacesLeft--; } // assemble the buffer: for each word, print the word, then a spaces block, and so on StringBuilder b = new StringBuilder(); for (int i = 0; i < words.length; i++) { b.append(words[i]); if (i < spaceBlocks.length) { b.append(spaceBlocks[i]); } } return b.toString();
}
public static void main(String [] args){String s; 字符串t;
s = "Hello, spaces."; t = formatString(s, 50); System.out.println(String.format("\\"%s\\" (length=%d)", t, t.length())); s = "Hello, spaces."; t = formatString(s, 51); System.out.println(String.format("\\"%s\\" (length=%d)", t, t.length())); s = "Good day, spaces."; t = formatString(s, 52); System.out.println(String.format("\\"%s\\" (length=%d)", t, t.length())); s = "The quick brown fox."; t = formatString(s, 53); System.out.println(String.format("\\"%s\\" (length=%d)", t, t.length())); s = "Ask not what your country can do for you."; t = formatString(s, 54); System.out.println(String.format("\\"%s\\" (length=%d)", t, t.length())); s = "Ask not what your country can do for you, Bob."; t = formatString(s, 55); System.out.println(String.format("\\"%s\\" (length=%d)", t, t.length()));
}
輸出,
"Hello, spaces." (length=50)
"Hello, spaces." (length=51)
"Good day, spaces." (length=52)
"The quick brown fox." (length=53)
"Ask not what your country can do for you." (length=54)
"Ask not what your country can do for you, Bob." (length=55)
在空格未包含所有偶數長度的空格的情況下,代碼傾向於將其放置在較早出現的空格中。
為了清楚起見,請注意,我沒有對邊緣情況進行編碼(一個單詞的字符串,零長度的輸出,空輸入,單詞不適合緩沖區等)。 留給讀者練習。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.