Saturday, 30 January 2021

Java12: String indent method

Signature

public String indent(int n)

 

Description

Adjusts the indentation of each line of this string based on the value of n, and normalizes line termination characters.

If n == 0, then line remains unchnages.

If n > 0, then n spaces are inserted at the beginning of each line.

If n < 0, then n spaces are removed from the beginning of each line.

 

Example

StringIndentExample.java

package com.sample.app.strings;

public class StringIndentExample {

	public static void main(String args[]) {
		String str = "       Hello World";
		String noIndenation = str.indent(0);
		String indet5Spaces = str.indent(5);
		String indentNegative5Spaces = str.indent(-5);

		System.out.println(str);
		System.out.println(noIndenation);
		System.out.println(indet5Spaces);
		System.out.println(indentNegative5Spaces);

	}

}

Output

       Hello World
       Hello World

            Hello World

  Hello World


Example 2: Format json string.

{

"id": 123,

"name": {

"firstName" : "Krishna",

"lastName" : "Gurram"

}

}

 

Following snippet formats the json string using indent method.

private static String getIndentedString() {
	StringBuilder builder = new StringBuilder();
	builder.append("{\n");
	builder.append("\"id\": 123,".indent(2));
	builder.append("\"name\": {".indent(2));
	builder.append("\"firstName\" : \"Krishna\",".indent(4));
	builder.append("\"lastName\" : \"Gurram\"".indent(4));
	builder.append("}".indent(2));
	builder.append("}");

	return builder.toString();
}


StringIndentExample2.java

package com.sample.app.strings;

public class StringIndentExample2 {

	private static String getIndentedString() {
		StringBuilder builder = new StringBuilder();
		builder.append("{\n");
		builder.append("\"id\": 123,".indent(2));
		builder.append("\"name\": {".indent(2));
		builder.append("\"firstName\" : \"Krishna\",".indent(4));
		builder.append("\"lastName\" : \"Gurram\"".indent(4));
		builder.append("}".indent(2));
		builder.append("}");

		return builder.toString();
	}

	public static void main(String args[]) {
		String s = getIndentedString();
		System.out.println(s);
	}

}


Output

{
  "id": 123,
  "name": {
    "firstName" : "Krishna",
    "lastName" : "Gurram"
  }
}


Reference

https://openjdk.java.net/jeps/326

 

 

 




 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment