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);
System.out.println(wrappedStr);
}
}
Output is –
Lorem ipsum dolor sit amet,
consectetur adipiscing
elit. Vestibulum non
turpis non nulla semper
eleifend. Proin tempus
tincidunt quam vitae
tristique.
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
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
See docs here.
That’s all about StringUtils wrap() Example in Java.
Related post.
- CollectionUtils isEmpty() Example in Java.
- StringUtils isEmpty() and IsBlank() Example in Java.
- StringUtils join() Example in Java.
- CollectionUtils union() Example in Java
- CollectionUtils intersection() Example in Java
- CollectionUtils isEqualCollection() Example in Java
- StringUtils isAlpha() example in Java
- StringUtils isNumeric() example in Java