简体   繁体   中英

Split Strings from an array of Strings

I want to extract lines from an array of strings, and split the ";" separator while stocking datas in an array. I know this is what the split method is supposed to do. But I can't get through. How should I process ?

public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String LON = in.next();
        String LAT = in.next();
        int N = in.nextInt();
        in.nextLine();
        String[] infoDefib=new String[N];                                  
        for (int i = 0; i < N; i++) {
            String DEFIB = in.nextLine();
            infoDefib[i]=DEFIB.split(";");
        }
        //System.out.println();
    }

The split function will split the String and store each of them into a String array.

ex: String[] strs = DEFIB.split(";");

You don't have to use a for loop and store them into String[] separately. New a String[] and equal to String.split("***"). Java will do it for you.

public static void main(String args[]) {
    Scanner in = new Scanner(System.in);
    //String LON = in.next();
    //String LAT = in.next();        
    String str = in.nextLine(); // use nextLine which you can read whole 
                                //line and store the data into a String
    in.nextLine();
    String[] infoDefib = DEFIB.split(";");//now you store them into a String array

String's split() method is pretty straight forward. You need to pass delimiter as an argument and it will return an array of string having string separated by provided delimiter.

Example :

String data = "This.is.simple.example.of.split.method";
String[] splitArray = data.split(".");//period(.) being delimeter
for (String val : splitArray) {
    System.out.println(val);
}

Result :

This
is
simple
example
of
split
method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM