1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.editor;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
/**
* @author hakon
*/
public class TextUtil {
private TextUtil() {}
/**
* Splits {@code text} by newline (LF {@code '\n'}).
*
* @param text the text to split into lines
* @param empty whether an empty text implies an empty List (true), or a List with one
* empty String element (false)
* @param prune whether a text ending with a newline will result in a List ending with the
* preceding line (true), or to add an empty String element (false)
*/
public static List<String> splitString(String text, boolean empty, boolean prune) {
List<String> lines = new ArrayList<>();
splitString(text, empty, prune, lines::add);
return lines;
}
/**
* Splits text by newline, passing each line to a consumer.
*
* @see #splitString(String, boolean, boolean)
*/
public static void splitString(String text,
boolean empty,
boolean prune,
Consumer<String> consumer) {
if (text.isEmpty()) {
if (!empty) {
consumer.accept(text);
}
return;
}
final int endIndex = text.length();
int start = 0;
for (int end = text.indexOf('\n');
end != -1;
start = end + 1, end = text.indexOf('\n', start)) {
consumer.accept(text.substring(start, end));
}
if (start < endIndex || !prune) {
consumer.accept(text.substring(start));
}
}
}
|