LoginSignup
0
0

More than 5 years have passed since last update.

Javaで、先頭と末尾のみから、複数の指定した文字をトリムしたい。

Last updated at Posted at 2018-07-23

先頭と末尾のみから、指定した複数の文字をトリムしたい。

結論

apache.commons.lang が使えない環境じゃない限りは
下記のコードの出番はないです。

stripメソッドを使いましょう。速いし。

これより先は、物好きの方のみ推奨。


たとえば。
全角スペース、半角スペース、タブ文字 以外の要素を取得したい。

なんてこと、よくある気がする。
都度、replaceAll?
「取り出したい要素の中にある半角スペース等は置き換えたくない」
 から、使えないんです。

そんな時に、下記コードを書きました。
コピペプログラマーの助けになれば幸いです。

    private String trim(String target) {
        if (target == null || target.isEmpty() || TRIM_CHARS.isEmpty()) {
            return target;
        }
        final char[] chars = target.toCharArray();
        int trimHeadIndex = 0;
        int trimTailIndex = 0;
        for (int i = 0; i < chars.length; i++) {
            if (!TRIM_CHARS.contains(chars[i])) {
                trimHeadIndex = i;
                break;
            }
        }
        for (int t = chars.length; t > 0; t--) {
            if (!TRIM_CHARS.contains(chars[t - 1])) {
                trimTailIndex = t;
                break;
            }
        }
        return target.substring(trimHeadIndex, trimTailIndex);
    }

TRIM_CHARS は配列なんだけれども
追加のし易さ的に、はじめはListで、
操作し終えた上で Collections#unmodifiableList にして、
定数として持っていたりするのが良いかも。
(final修飾子だけじゃなくて、ね)

「正規表現使っても出来そうだなぁ。」と今更思ったけど、
実現できてるから、いいか。

ちなみに、サロゲートペア文字で実験しても期待通り動いてくれました。
(想定外でしたが)

0
0
2

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
0