[Android] Add an arbitrary character string at the beginning of multiple lines

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.

Thing you want to do

this

foo
bar
baz

↓ I want to do this

>foo
>bar
>baz

code

A pattern that works hard

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, ">");

(Addition) Pattern using join

String newLineCode = "\r\n";
String prefixedText = prefix + String.join(newLineCode + prefix, text.split(newLineCode, 0));

Thank you @Kilisame!

(Addition) Patterns that use regular expressions

public String A(String text, String prefix) {
    return text.replaceAll("(?m)^.*$", prefix + "$0");
}

Thank you @ saka1029!

Supplement

It seems easier if you use regular expressions.

Recommended Posts

[Android] Add an arbitrary character string at the beginning of multiple lines
[Ruby] Insert, replace, destroy at the end of the character string [b021]
[Delete the first letter of the character string] Ruby
About truncation by the number of bytes of String on Android
[Android] Exit the activity of the transition source at the time of screen transition
The basics of the process of making a call with an Android app
A solution to the problem of blank spaces at the beginning of textarea
[Android Studio] Set an arbitrary image for the application background [Java]
[Rails] How to omit the display of the character string of the link_to method