LoginSignup
0
2

More than 5 years have passed since last update.

【Android】複数行の行頭に任意の文字列を追加する

Last updated at Posted at 2017-06-25

コメント引用機能を実装するときに引用文字(">"など)を行頭に追加したいときがあったのでそのコードのメモです。

やりたいこと

これを

foo
bar
baz

↓こうしたい

>foo
>bar
>baz

コード

真面目に頑張るパターン

prefixを各行の行頭付与するメソッド

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;
}

呼び出し

String prefixedText = A(text, ">");

(追記)joinを使うパターン

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

@Kilisame さんありがとうございます!

(追記)正規表現を使うパターン

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

@saka1029 さんありがとうございます!

補足

正規表現使えばもっと簡単にできそう。

0
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2