如何通过元素拆分字符串数组

时间:2015-09-15 04:15:40

标签: java

如何通过元素拆分String []预订。例如

Tokens[0] = 8  
Tokens[1] = 2  
Tokens[2] = Nobbly, Greg  
Tokens[3] = Nobbly, Jo-Anne  
Tokens[4] = 1  
Tokens[5] = Lee, Sook


public static String[] BookingList()
      {
        String[] bookings = new String[]{"8","2","Nobbly, Greg","Nobbly, Jo-Anne","1","Lee, Sook","3","Lukas, Stephie","Lukas, Cambridge","Lukas, Ogden"}; 
        String[] tokens = new String[bookings.length];
        for(int i = 0; i < bookings.length; i++)
        {
          tokens = bookings[i].trim().split(",");
        }
        return tokens;
      }

2 个答案:

答案 0 :(得分:1)

元素已存在于String数组String[] bookings = new String[]{"8","2","Nobbly, Greg","Nobbly, Jo-Anne","1","Lee, Sook","3","Lukas, Stephie","Lukas, Cambridge","Lukas, Ogden"}; for(String booking: bookings) { System.out.println(booking); } 中。您可以通过简单打印来检查它:

8
2
Nobbly, Greg
Nobbly, Jo-Anne
1
Lee, Sook
3
Lukas, Stephie
Lukas, Cambridge
Lukas, Ogden

打印:

tokens

您可以通过撰写代码bookings来引用String[] tokens = bookings;

tokens

需要注意的是,现在bookings和{{1}}都引用相同的字符串数组。

答案 1 :(得分:0)

使用流式api(为了更好的性能)和分割(正则表达式)

String[] bookings = new String[]{"8", "2", "Nobbly, Greg", "Nobbly, Jo-Anne", "1", "Lee, Sook", "3", "Lukas, Stephie", "Lukas, Cambridge", "Lukas, Ogden"};
ArrayList<String> tokens = new ArrayList<>();
Arrays.asList(bookings).forEach((String booking) -> {
    tokens.addAll(Arrays.asList(booking.split("\\s*,\\s*")));      //split booking into array and add as token in 'tokens'
});
System.out.println(tokens);