Java-Array Splitting

时间:2014-11-28 06:53:43

标签: java split

我有一串字符串{"All-Inclusive,All Inclusive","Luxury,Luxury","Spa-And-Relaxation,Spa & Relaxation"}

我想基于“,”将它们拆分为两个数组,第一个数组{"All-Inclusive","Luxury","Spa-And-Relaxation"}和第二个数组{"All Inclusive","Luxury","Spa & Relaxation"}

你能否建议怎么做?

1 个答案:

答案 0 :(得分:0)

您可以迭代String(s)的数组。对于每个元素,调用String.split(String),这将产生一个临时数组。确保您从数组中获得两个String,然后将其分配给您的输出firstsecond,如

public static void main(String[] args) {
    String[] arr = { "All-Inclusive,All Inclusive", "Luxury,Luxury",
            "Spa-And-Relaxation,Spa & Relaxation" };
    String[] first = new String[arr.length];
    String[] second = new String[arr.length];
    for (int i = 0; i < arr.length; i++) {
        String[] t = arr[i].split("\\s*,\\s*");
        if (t.length == 2) {
            first[i] = t[0];
            second[i] = t[1];
        }
    }
    System.out.printf("First = %s%n", Arrays.toString(first));
    System.out.printf("Second = %s%n", Arrays.toString(second));
}

输出

First = [All-Inclusive, Luxury, Spa-And-Relaxation]
Second = [All Inclusive, Luxury, Spa & Relaxation]