あなたが知らないJavaのsplitの小さな問題


詳細
時には、私たちのいくつかのビジネスデータは、ある分割子によってデータを分割し、1行1行で処理することを定義しています.このデータを処理するときは、json形式のようなデータやオブジェクトを維持するのではなく、直接下の位置を通ってデータにアクセスすることに注意してください.このようなシーンは誰もが接触したことがあると信じています.もちろん弊害も明らかですが、位置を間違えたり、コードの使用が不適切になったりすると、いくつかの問題が発生します.そのため、この方法を使用すると、行区切り記号、列分割記号など、いくつかの内容が約束されます.次の小さな問題を見てみましょう.まず、次のコードを見てみましょう.

      String line1="1#2#3";//    3,   3
        System.out.println(line1.split("#").length);

        String line2="1#2#3##";//    5,     3 ,    ? 
        System.out.println(line2.split("#").length);


実行が終わると、2番目のコードの配列の長さがあなたの考えと一致しないことがわかりますか?どうして?公式サイトapiの説明を見てみましょう.

/**
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
*/

public String[] split(String regex,int limit)

 


limitが負数の場合、この配列のすべての個数にできるだけ一致し、0の場合、出現する要素にできるだけ一致しますが、空の文字列は破棄されますが、破棄することは望んでいません.破棄はビジネスフィールドが欠落していることを意味します.

        String line3="1#2#3##";//      
        System.out.println(line3.split("#",-1).length);