Languages
[Edit]
EN

Java - add tabulator to each one line in text

7 points
Created by:
Flimzy
356

In this short article, we would like to show how to add a tabulator to each one line in text using Java.

Quick solution:

package com.example;

public class Program {

    public static void main(String[] args) {

        String tabulators = "\t\t";  // 2 tabs

        String text = "abc\n" +
                      "123\n" +
                      "456\n";

        String result = TextUtils.tabulateText(tabulators, text);

        System.out.println(result);
    }
}

Output:

		abc
		123
		456

TextUtils.java file:

package com.example;

import java.util.regex.Pattern;

public class TextUtils {

    private static final Pattern NEWLINE_PATTERN = Pattern.compile("\\r\\n|\\n\\r|\\n|\\r");

    public static String tabulateText(String tabulators, String text) {
        String[] lines = NEWLINE_PATTERN.split(text);
        if (lines.length == 1) {
            return tabulators + text;
        }
        StringBuilder result = new StringBuilder();
        for (String line : lines) {
            result.append(tabulators + line + "\n");
        }
        return result.toString();
    }
}

See also

  1. Java - split string by new line character 
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join