Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is StringUtils.chomp in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

chomp is a static method of the StringUtils class that is used to remove the last occurring newline character in a given string. If the string ends with multiple newline characters, then only the last occurring newline character is removed.

Below are the newline characters:

  • \n
  • \r
  • \r\n

StringUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml file.

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

Note: For other versions of the commons-lang package, refer to the Maven Repository.

You can import the StringUtils class as follows:

import org.apache.commons.lang3.StringUtils;

Syntax

public static String chomp(final String str)

Parameters:

  • final String str: the string from which the last occurring newline character is removed.

Return value

chomp returns the edited string without the last occurring newline character.

Code

import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
System.out.println("\"" + StringUtils.chomp("AbaBAaaa\n\n \tsjadfng\n\r\n") + "\"");
System.out.println("\"" + StringUtils.defaultString("hello\n\t educative\n\n") + "\"");
}
}

Output

"AbaBAaaa

  	sjadfng
"
"hello
	 educative

"

The \r\n characters from the first string are removed. The last character \n is removed from the second string.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring