Bipa
Bipa

Reputation: 319

Splitting string on certain word into ArrayList - java

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"?

Upvotes: 2

Views: 17069

Answers (2)

juergen d
juergen d

Reputation: 204884

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));

Upvotes: 9

Vikdor
Vikdor

Reputation: 24134

Assuming that you still want to return a list of strings when the input string doesn't have the character on which you are splitting, Arrays.asList(inputString.split(" ")) should work.

E.g. Arrays.asList("farmersmarket".split(" ")) would return a list that contains only one element--farmersmarket.

Upvotes: 0

Related Questions