Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting string on certain word into ArrayList - java

Tags:

java

string

split

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

like image 691
Bipa Avatar asked Jun 21 '26 05:06

Bipa


1 Answers

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));
like image 134
juergen d Avatar answered Jun 23 '26 19:06

juergen d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!