2014-01-10 26 views
3

我試圖實現一種方法,它需要一個文本和一列的寬度並輸出文本,每行限於列寬。Java中println()語句的字符數限制

public void wrapText(String text, int width) 
{ 
    System.out.println(text); 
} 

例如,調用與文本的方法是:

 
Triometric creates unique end user monitoring products for high-value Web 
    applications, and offers unrivalled expertise in performance consulting. 

與列寬20會導致下面的輸出:

 
Triometric creates 
unique end user 
monitoring products 
for high-value Web 
applications, and 
offers unrivalled 
expertise in 
performance 
consulting. 
+1

迭代字符串的字符並在每個寬度後面添加一個'\ n' –

+1

mm,不是那麼容易@kocko。這可能會導致一個字中間出現分界線! –

+0

這就是說,@ user3182511,如果'width'小於一個字長度會發生什麼?是否將連字符作爲第20個字符插入一行,然後該行的其餘部分是否繼續? –

回答

3

你可以嘗試這樣的事情:

public static void wrapText(String text, int width) { 
    int count = 0; 

    for (String word : text.split("\\s+")) { 
     if (count + word.length() >= width) { 
      System.out.println(); 
      count = 0; 
     } 

     System.out.print(word); 
     System.out.print(' '); 

     count += word.length() + 1; 
    } 
} 

儘管如果方法的結果不明確(例如,單個單詞的長度大於width),則仍然是這種情況。上面的代碼將簡單地在自己的行上打印這樣一個詞。

+0

+1不要使用'for(String s:split){...'? –

+0

@tobias_k是的,我認爲這會更好。我會編輯。 – arshajii

0

我將通過分割在whitelines字符串,然後通過文字印刷的字,這樣做:

public static void wrapText(String text, int width) throws Exception { 
    String[] words = text.split(" "); 
    int acsize = 0; 
    for (String word : words) { 

     if (word.length() > width) { 
      throw new Exception("Word longer than with!"); 
     } 
     if (acsize + word.length() <= width) { 
      System.out.print(word + " "); 
      acsize += word.length() + 1; 
     } else { 
      System.out.println(); 
      System.out.print(word + " "); 
      acsize = word.length() + 1; 
     } 
    } 
} 

唯一的例外可能只是刪除,如果你想打印的單詞比寬度更長,像你在你上次評論時說。