Remove Newline, Space, and Tab Characters from a String in Java



To remove newline, space and tab characters from a string, replace them with empty as shown below.

replaceAll("[\n\t ]", "");

Above, the new line, tab, and space will get replaced with empty, since we have used replaceAll()

The following is the complete example.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String originalStr = "Demo\n\tText";
      System.out.println("Original String with tabs, spaces and newline: \n"+originalStr);
      originalStr = originalStr.replaceAll("[\n\t ]", "");
      System.out.println("\nString after removing tabs, spaces and new line: "+originalStr);
   }
}

Output

Original String with tabs, spaces and newline:
Demo
Text
String after removing tabs, spaces and new line: DemoText
Updated on: 2020-06-27T06:36:38+05:30

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started