EN
Java - add tabulator to each one line in text
7 points
In this short article, we would like to show how to add a tabulator to each one line in text using Java.
Quick solution:
xxxxxxxxxx
1
package com.example;
2
3
public class Program {
4
5
public static void main(String[] args) {
6
7
String tabulators = "\t\t"; // 2 tabs
8
9
String text = "abc\n" +
10
"123\n" +
11
"456\n";
12
13
String result = TextUtils.tabulateText(tabulators, text);
14
15
System.out.println(result);
16
}
17
}
Output:
xxxxxxxxxx
1
abc
2
123
3
456
TextUtils.java
file:
xxxxxxxxxx
1
package com.example;
2
3
import java.util.regex.Pattern;
4
5
public class TextUtils {
6
7
private static final Pattern NEWLINE_PATTERN = Pattern.compile("\\r\\n|\\n\\r|\\n|\\r");
8
9
public static String tabulateText(String tabulators, String text) {
10
String[] lines = NEWLINE_PATTERN.split(text);
11
if (lines.length == 1) {
12
return tabulators + text;
13
}
14
StringBuilder result = new StringBuilder();
15
for (String line : lines) {
16
result.append(tabulators + line + "\n");
17
}
18
return result.toString();
19
}
20
}