Splitting string on certain word into ArrayList - java

16,525
String[] tokens = yourString.split("farmersmarket");

And afterwards you don't need an Arraylist to get a specific element of the tokens. You can access every token like this

String firstToken = tokens[0];
String secondToken = tokens[1];

If you need a List you can do

List<String> list = Arrays.asList(tokens);

and if it has to be an Arraylist do

ArrayList<String> list = new ArrayList<String>(Arrays.asList(tokens));
Share:
16,525
Bipa
Author by

Bipa

Updated on June 18, 2022

Comments

  • Bipa
    Bipa almost 2 years

    I am stuck splitting a string into pieces to store the pieces into an ArrayList. I can split the string onto " ", but I'd like to split the string onto "farmersmarket" and store it into an Arraylist. To be able to return one of the indexed pieces of string.

        ArrayList<String> indexes = new ArrayList<String>();
        String s = file; 
    
        for(String substring: s.split(" ")){
            indexes.add(substring);
            }
        System.out.println(indexes.get(2));
    

    Any ideas to split a string on "farmersmarket"?

  • Bipa
    Bipa almost 12 years
    Can I do store them in an ArrayList? I need the ArrayList to do something more with the strings.