2014-01-10 3 views
3

텍스트 문자열과 열 너비를 사용하고 각 열을 열 너비로 제한하는 메서드를 구현하려고합니다. 열 너비 20Java에서 println() 문의 문자 수 제한

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

는 다음과 같은 출력을 초래할 것 :

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

문자열의 문자를 반복하고 'width'번째 문자 다음에 '\ n'을 추가하십시오. –

+1

음, 그렇게 쉽지 않습니다. @kocko. 단어 중간에 줄 바꿈이 생길 수 있습니다. –

+0

즉, @ user3182511라고하면 'width'가 단어 길이보다 작 으면 어떻게 될까요? 한 줄에 20 번째 문자로 삽입 된 하이픈이 있으면 나머지 줄이 계속됩니까? –

답변

3

당신은 이런 식으로 뭔가를 시도 할 수 있습니다 : 텍스트와 메소드를 호출 예를 들어

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

,

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; 
     } 
    } 
} 

예외 그냥 제거 될 수

, 당신이 원하는 경우처럼, 단어에게 폭 이상을 인쇄하려면 마지막으로 당신이 말했습니다.