Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format text output for console in Java

I'm writing a simple diary console program. Can't really figure out what the easiest way to break up text input from the user. I take in a diary note in a string and then I want to be able to print that string to the console, but unformatted it of course just shows the string in one long line across the terminal making it terribly unfriendly to read. How would I show the string with a new line for every x characters or so? All I can find about text formatting is System.out.printf() but that just has a minimum amount of characters to be printed.

like image 592
mistysch Avatar asked Nov 18 '25 06:11

mistysch


1 Answers

I would recommend to use some external libraries to do, like Apache commons:

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html

and using

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#wrap(java.lang.String, int)

static final int FIXED_WIDTH = 80;

String myLongString = "..."; // very long string
String myWrappedString = WordUtils.wrap(myLongString,FIXED_WIDTH);

This will wrap your String, respecting spaces ' ', with a fixed width

WITHOUT EXTERNAL LIBRARIES

You will have to implement it:

BTW: I dont have a compiler of java here to test it, so dont rage if it does not compile directly.

private final static int MAX_WIDTH = 80;

public String wrap(String longString) {
    String[] splittedString = longString.split(" ");
    String resultString = "";
    String lineString = "";

    for (int i = 0; i < splittedString.length; i++) {
        if (lineString.isEmpty()) {
            lineString += splittedString[i];
        } else if (lineString.length() + splittedString[i].length() < MAX_WIDTH) {
            lineString += splittedString[i];
        } else {
            resultString += lineString + "\n";
            lineString = "";
        }
    }

    if(!lineString.isEmpty()){
            resultString += lineString + "\n";
    }

    return resultString;
}
like image 97
RamonBoza Avatar answered Nov 20 '25 19:11

RamonBoza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!