Array list not getting split properly

孤者浪人 提交于 2020-07-09 12:16:30

问题


The value ALL||test > test's done> test's done again's done||test > test's done> test's done again's done 2 is an array list

what i want to do is have a list separated by ||

so the first element is :

ALL

second:

test > test's done> test's done again's done

last:

test > test's done> test's done again's done 2

code i wrote:

String record1 = record.toString();
        String[] parts = record1.split("||");
        
        for (int i = 1; i <= parts.length; i++) {
              System.out.println(parts[i]);
            }

What i'm getting is each letter by itself and at the end a ] character which is unwanted as well.


回答1:


You can split by using the following code:

    String [] parts = record1.split("\\|\\|");

Also, the code written above won't work as the loop is running from 1 to parts.length instead of 0 to parts.length-1.




回答2:


| is a metacharacter and therefore, you need to escape it using a \. Since \ itself is a metacharacter, you need another \ to escape the \. Thus, you need to use \\|\\| as the regex.

public class Main {
    public static void main(String[] args) {
        String[] parts = "ALL||test > test's done> test's done again's done||test > test's done> test's done again's done 2"
                .split("\\|\\|");
        for (String s : parts) {
            System.out.println(s);
        }
    }
}

Output:

ALL
test > test's done> test's done again's done
test > test's done> test's done again's done 2

Another problem with your code is that the range of your loop counter is 1 to length_of_ the_array whereas the indices of a Java array are in the range of 0 to (length_of_ the_array - 1). Therefore, if you want to access the elements of the array using their indices, your code should be:

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


来源:https://stackoverflow.com/questions/62745106/array-list-not-getting-split-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!