When implementing the comment citation function, I sometimes wanted to add a citation character (such as ">") at the beginning of a line, so this is a memo of that code.
this
foo
bar
baz
↓ I want to do this
>foo
>bar
>baz
A method that assigns a prefix to the beginning of each line
public String A(String text, String prefix) {
String prefixedText = "";
String newLineCode = "\r\n";
String[] lines = text.split(newLineCode, 0);
for (String line : lines) {
prefixedText += prefix + line + newLineCode;
}
return prefixedText;
}
call
String prefixedText = A(text, ">");
String newLineCode = "\r\n";
String prefixedText = prefix + String.join(newLineCode + prefix, text.split(newLineCode, 0));
Thank you @Kilisame!
public String A(String text, String prefix) {
return text.replaceAll("(?m)^.*$", prefix + "$0");
}
Thank you @ saka1029!
It seems easier if you use regular expressions.
Recommended Posts