簡體   English   中英

Java - 如何根據輸入將字符串拆分為多行?

[英]Java - How would I split a string into multiple lines depending on an input?

我是 Java 的新手,我想根據輸入的最大長度將用戶輸入的消息拆分為多行。 我將如何重復它? 這是我到目前為止所擁有的:

int rem = m - maxlength;
System.out.println(message.substring(0, message.length() - rem));
System.out.println(message.substring(message.length() - rem)); 

正則表達式版本(最簡單):

String text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
int lineMaxLength = 10;
System.out.println(java.util.Arrays.toString(
    text.split("(?<=\\G.{"+lineMaxLength+"})")
));

哪個打印:

[Lorem Ipsu, m is simpl, y dummy te, xt of the , printing a, nd typeset, ting indus, try. Lorem,  Ipsum has,  been the , industry's,  standard , dummy text,  ever sinc, e the 1500, s, when an,  unknown p, rinter too, k a galley,  of type a, nd scrambl, ed it to m, ake a type,  specimen , book.]

沒有正則表達式:

import java.util.List;
import java.util.ArrayList;

public class MyClass {
    public static void main(String args[]) {
      String text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
      int lineMaxLength = 10;
      List<String> lines = new ArrayList<>();
      int length = text.length();
      StringBuilder s = new StringBuilder();
      for(int i = 0; i < length; i++){
          if (i % lineMaxLength == 0){
              if(i != 0){
                  lines.add(s.toString());
              }
              s = new StringBuilder();
          }
          s.append(text.charAt(i));
      }
  int linesLength = lines.size();
  for(int i= 0; i < linesLength; i++){
      System.out.println(lines.get(i));
  }
    }
}

哪個打印:

Lorem Ipsu
m is simpl
y dummy te
xt of the 
printing a
nd typeset
ting indus
try. Lorem
 Ipsum has
 been the 
industry's
 standard 
dummy text
 ever sinc
e the 1500
s, when an
 unknown p
rinter too
k a galley
 of type a
nd scrambl
ed it to m
ake a type
 specimen 

這類作品。 我選擇了一個非常短的 10 個字符的“行”長度,您可能應該增加它。 但它展示了如何在沒有太多代碼的情況下做到這一點。 將正則表達式中的“10”更改為不同的數字以增加行長。

(我稍微更改了代碼以更明顯地表明此方法不會在中間拆分單詞,而是始終在空白處拆分。)

   public static void main( String[] args ) {
      String s = "This is a test. This is a test. This is a test. This is a test. This is a test. This is a test.  ";
      String regex = ".{1,10}\\s";
      Matcher m = Pattern.compile( regex ).matcher( s );
      ArrayList<String> lines = new ArrayList<>();
      while( m.find()  ) {
         lines.add(  m.group() );
      }
      System.out.println( String.join( "\n", lines ) );
   }

跑:

This is a 
test. This 
is a test. 
This is a 
test. This 
is a test. 
This is a 
test. This 
is a test. 
BUILD SUCCESSFUL (total time: 0 seconds)

       

像這樣使用 WordIterator。 BreakIterator 類對語言環境敏感。 您可以使用不同的語言。

public static void main(String[] args) {
    String msg = "This is a long message. Message is too long. Long is the message";
    int widthLimit = 15;
    printWithLimitedWidth(msg, widthLimit);
}

static void printWithLimitedWidth(String s, int limit) {
    BreakIterator br = BreakIterator.getWordInstance(); //you can get locale specific instance to handle different languages.
    br.setText(s);
    int currLenght = 0;
    int start = br.first();
    int end = br.next();

    while (end != BreakIterator.DONE) {
       String word = s.substring(start,end);
       currLenght += word.length(); 
       if (currLenght <= limit) {
          System.out.print(word);
       } else {
           currLenght = 0;
           System.out.print("\n"+word);
       }
       start = end;
       end = br.next();
    }
}

Output:

This is a long 
message. Message is 
too long. Long is 
the message

這是一個示例代碼。 根據您的需要處理空格和其他特殊字符。 有關更多信息,請參閱https://docs.oracle.com/javase/tutorial/i18n/text/about.html

int maxlength = 10;
String message = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String transformedMessage = message.replaceAll("(?<=\\G.{" + maxlength + "})", "\n");
System.out.println(transformedMessage);
/*Output
1234567890
ABCDEFGHIJ
KLMNOPQRST
UVWXYZ
*/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM