Tuesday, March 02, 2021

Techniques for including leading white spaces into text blocks

We saw one approach for controlling leading indentation by moving the ending three double quotes position as required. 

But a scenario in which this approach would not work is when we do not want a new line after the last line of the text block. The code then becomes

        String poemTextBlock = """
                <html>
                    <body>
                        <pre>
                            The woods are lovely, dark and deep,
                            But I have promises to keep,
                            And miles to go before I sleep,
                            And miles to go before I sleep.
                        </pre>
                    </body>
                </html>""";

Here we will not be able to use the position of """ to dictate leading indentation required. 

We will have to use the indent() method on string to provide the necessary indentation. Code for this  shown in the below sample below

public class Main {

    public static void main(String[] args) {

        String poemTextBlock = """
                <html>
                    <body>
                        <pre>
                            The woods are lovely, dark and deep,
                            But I have promises to keep,
                            And miles to go before I sleep,
                            And miles to go before I sleep.
                        </pre>
                    </body>
                </html>""".indent(8);
    
        System.out.println(poemTextBlock);
    }
}


Sample code used in this post can be downloaded from https://github.com/ashokkumarta/awesomely-java/tree/main/2021/03/Language-Features/Text-blocks/Techniques-for-including-leading-white-spaces


No comments:

Post a Comment