简体   繁体   English

Java - 如何根据输入将字符串拆分为多行?

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

I am new to Java and want to split a message that a user inputs into multiple lines depending on what has been inputted as the maximum length.我是 Java 的新手,我想根据输入的最大长度将用户输入的消息拆分为多行。 How would I go about repeating it?我将如何重复它? Here is what I have so far:这是我到目前为止所拥有的:

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

Regex version (simplest):正则表达式版本(最简单):

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+"})")
));

Which prints:哪个打印:

[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.]

Without regex:没有正则表达式:

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

Which prints:哪个打印:

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 

This sort of works.这类作品。 I picked a very short "line" length of 10 characters, you should probably increase this.我选择了一个非常短的 10 个字符的“行”长度,您可能应该增加它。 But it shows how you might do this without too much code.但它展示了如何在没有太多代码的情况下做到这一点。 Cheange the "10" in the regex to a different number to increase the line length.将正则表达式中的“10”更改为不同的数字以增加行长。

(I changed the code a bit to make it more obvious that this method does not split words in the middle but always splits at a white space.) (我稍微更改了代码以更明显地表明此方法不会在中间拆分单词,而是始终在空白处拆分。)

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

run:跑:

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)

       

Use WordIterator like this.像这样使用 WordIterator。 BreakIterator classes are locale sensitive. BreakIterator 类对语言环境敏感。 You can use with different languages.您可以使用不同的语言。

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: Output:

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

This is a sample code.这是一个示例代码。 Handle white space and other special characters according to your needs.根据您的需要处理空格和其他特殊字符。 For more info refer https://docs.oracle.com/javase/tutorial/i18n/text/about.html有关更多信息,请参阅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