2010-12-14 8 views
2

区切り文字が '、'(コンマ)であると仮定すると、返されるString []配列が特定のサイズmore、no less):特定のサイズの文字列[]に文字列を分割する

String[] split(String str, int limit); 

split("hello", 2);    => ["hello", ""] 
split("hello,", 2);    => ["hello", ""] 
split(",hello", 2);    => ["", "hello"] 
split("hello,world", 2);   => ["hello", "world"] 
split("hello,world,goodbye", 2); => ["hello", "world,goodbye"] 

配列のサイズは常に2になっていますか?私はPattern.splitでこの動作のいくつかを得ることができますが、すべてのケースではありません...どうすればいいですか?

+0

私はちょうどそれが必要として働いているあなたの問題、 'Pattern.splitを()'が表示されません。これらの呼び出しで常にサイズ2の配列が返されるようです。 – Poindexter

+0

@Poindexter - 実際はそうではありません - 'split'は最大数を定義しますが、それよりも少ない場合は少なく返します。 Juliaは空の文字列でその結果を埋めたいと思っています。 – Kobi

答えて

1

StringUtils.split(string, separator, max)は、あなたが必要とするものに非常に近いです。

次にArrayUtils.addAll(result, emptyArray)を使用できます。emptyArrayは、サイズがmax - result.lengthの配列です。

あなたが望む機能はあまりにも特殊なので、すぐに使用できるものはないと思います。

+0

これは私の最終的な解決策に最も近いものでした。 – Julia

0

私は心ですべての構文を覚えていないが、あなたはこのような何かを見ている:

Pattern p = new Pattern("[^,]+"); 
String[] strings = new String[limit]; 
int offset = 0; 
int i = 0; 
for (; i < limit; i++) { 
    Match m = str.match(p, offset); 
    if (m == null) break; 
    offset += m.string.length + 1; 
    strings[i] = m.string; 
} 
for (; i < limit; i++) { 
    strings[i] = ""; 
} 

繰り返しますが、これはない有効なJava

0

は、それが可能だろうと思わあり空の文字列で新しい配列をパディングするのに十分なほど簡単です。この分割を実行するために使用できるユーティリティメソッドを次に示します。

public static String[] split(Pattern pattern, CharSequence input, int limit) { 
    // perform the split 
    tokens = pattern.split(input, limit); 

    int tokenCount = tokens.length(); 
    if (tokenCount == limit) { 
     // if no padding is necessary, return the result of pattern.split 
     return tokens; 
    } else { 
     // create a new array, copy tokens into array, pad with empty string 
     String[] padded = Arrays.copyOf(tokens, limit); 
     for (int i = tokenCount; i < limit; i++) { 
      padded[i] = ""; 
     } 
     return padded; 
    } 
} 

編集:恥知らずunholysampler's answerから[1]〜[Arrays.copyOf]盗むために更新。

[1]:http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#copyOf(T[]、int型)

0

まあ、私はあなたがちょうどあなたが引数を介して提供回数に達しているとすぐに分裂を停止し、最後に完全に残りのビットを移動したい正しくあなたを理解している場合フィールド、右?さらに、limit-parameterは常にfieldcountを保証する必要がありますか?

制限/しきい値/最小に達するまでフィールドを追加するだけのPattern.split()メソッドでメソッドをラップします。

あなたは、区切り文字を検索文字列をスキャンループでそれを行うその後、先に配列の区切り文字のないものは何でも入れて、それはトップの配列のサイズに到達するまで、それを再度行う、という可能性が
for(i=0;i<limit;++i){ 
//add empty fields to array until limit is reached 
} 
0

それだけで、配列の最後のエントリとして先駆けだったものは何でも返す方法:

public string[] mySplit(String Split, char Delimiter, int Top) 
{ 
    string[] returned = new string[Top]; 
    for(int i = 0; i < Top; i++){ 
    if(i==Top) 
    { 
    returned[i] = Split; return; 
    } 
    else 
    { 
    int compPlace = 0; 
    char comp = Split.toCharArray()[compPlace]; 
    while(comp != Delimiter) 
    { 
     compPlace++; 
     comp = Split.toCharArray()[compPlace]; 
     } 
    returned[i] = Split.SubString(0,compPlace); 
    Split = Split.SubString(compPlace); 
    } 
    } 
    return returned; 
} 

イムyoullのは、私は今のところ少し頭痛を持っているとして、これを微調整するために持っていることを確認:)

2

あなたが返すようにArrays.copyOf()を使用することができますパディングされた配列ただし、パディングは空の文字列の代わりにnullになります。

String[] parts = Arrays.copyOf("hello,".split(",", 2), 2); 
String[] parts1 = Arrays.copyOf(",hello".split(",", 2), 2); 
String[] parts2 = Arrays.copyOf("hello,world".split(",", 2), 2); 
String[] parts3 = Arrays.copyOf("hello,world,goodbye".split(",", 2), 2); 
String[] parts4 = Arrays.copyOf("hello,".split(",", 2), 4); //null padding 
0

単に区切りの位置を取得し、サブストリングを使用してはかなり簡単にそこにあなたを取得:

public static String[] split(String str, int limit){ 

      String[] arr = new String[limit]; 

      for(int i = 0; i < limit-1; i++){ 
       int position = str.indexOf(','); 
       int length = str.length(); 

       if(position == -1){ 
        arr[i]= str.substring(0,length); 
        str = str.substring(length, length); 
       } 
       else{ 
        arr[i] = str.substring(0, position); 
        str = str.substring(position+1, length); 
       } 
      } 

      arr[limit-1] = str; 

      return arr; 
     } 
関連する問題