-2

I've been trying to split an string by a character and store each split value inside an array. In C# it can be done by calling the .ToArray() method after the Split() but such method apparently doesn't exits in Java. So I've been trying to do this like this (rs is a string list with elements separated by #) :

    String t[] = new String[10];
    for (int i = 0; i < rs.size(); i++) {
        t = null;
        t = rs.get(i).split("#");
    }

But the whole split line is passed to an index of the array like:

String x = "Hello#World"  -> t[0] = "Hello World" (The string is split in one line, so the array will have only one index of 0)

My question is that how can store each spit element in an index of the array like :

t[0] = "Hello"
t[1] = "World"
4

4 に答える 4

1

リストをループして分割し、配列を一緒に追加しようとしているように聞こえますか? .split メソッドの問題として定義しているのは、まさに split メソッドが行うことです。

    ArrayList<String> rs = new ArrayList<>();
    rs.add("Hello#World");
    rs.add("Foo#Bar#Beckom");

    String [] t = new String[0];
    for(int i=0;i<rs.size();i++) {
        String [] newT = rs.get(i).split("#");
        String [] result = new String[newT.length+t.length];
        System.arraycopy(t, 0, result, 0,  t.length);
        System.arraycopy(newT, 0, result, t.length, newT.length);
        t = result;
    }

    for(int i=0;i<t.length;i++) {
        System.out.println(t[i]);
    }

出力を見つけるだけで動作します:

Hello
World
Foo
Bar
Beckom
于 2013-09-14T22:10:56.427 に答える
1

この方法を試してください:

String string = "Hello#World"
String[] parts = string.split("#");
String part1 = parts[0]; // Hello
String part2 = parts[1]; // World

文字列に # (この場合) が含まれているかどうかを事前にテストすることをお勧めします。単にString#contains()を使用してください。

if (string.contains("#")) {
    // Split it.
} else {
    throw new IllegalArgumentException(message);
}
于 2013-09-14T22:06:30.550 に答える
1
public class Test {
public static void main(String[] args) {
    String hw = "Hello#World";

    String[] splitHW = hw.split("#");

    for(String s: splitHW){
        System.out.println(s);
    }
}
}

これにより、次の出力が生成されました。

Hello
World
于 2013-09-14T22:20:33.727 に答える
0

問題がすでにJavaで解決されているのに、なぜループを使用しているのですか..これを試してください

String x = "Hello#World";
String[] array = x.split("#", -1);

System.out.println(array[0]+" "+array[1]);
于 2013-09-14T22:02:19.500 に答える