Tuesday 26 October 2021

Java: Replace spaces by new line character

Below statement replace spaces by single new line character.

 

str.replaceAll("\\s+", System.lineSeparator());

 

Find the below working application.

 

ReplaceSpacesByNewLine.java

package com.sample.app.strings;

public class ReplaceSpacesByNewLine {

	public static String replaceSpacesByNewLine(String str) {
		return str.replaceAll("\\s+", System.lineSeparator());
	}

	public static void main(String args[]) {
		System.out.println(replaceSpacesByNewLine("Hi How   are you"));
	}

}

 

Output

Hi
How
are
you

 

 

 

 

You may like

No comments:

Post a Comment