StringUtils wrap() Example in Java

In this post, we will see org.apache.commons.lang3.StringUtils wrap() example in Java.

import org.apache.commons.lang3.StringUtils;

public class StringUtilsExample {
    public static void main(String[] args) {
        String str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                     "Vestibulum non turpis non nulla semper eleifend. " +
                     "Proin tempus tincidunt quam vitae tristique.";
        String wrappedStr = StringUtils.wrap(str, 30, "\n\t", false);

Output is –

Lorem ipsum dolor sit amet,
consectetur adipiscing
elit. Vestibulum non
turpis non nulla semper
eleifend. Proin tempus
tincidunt quam vitae

In this example, we import the StringUtils class from the Apache Commons Lang library, and then define a long string str that we want to wrap at a maximum line length of 30 characters. We then use the wrap() method to wrap the string, passing in the str variable, the maximum line length of 30, the prefix string “\n\t” to insert at the beginning of each wrapped line (which will add a newline and tab character to each wrapped line), and the false flag to indicate that we do not want to wrap words. The resulting wrapped string is stored in the wrappedStr variable, and then printed to the console using System.out.println().

We need to add the below dependency in pom.xml to use org.apache.commons.lang3.StringUtils wrap() method. We can download the apache-commons maven dependency from here.

pom.xml changes


See docs here.

That’s all about StringUtils wrap() Example in Java.

Related post.