将某个单词上的字符串拆分为 ArrayList - java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11911862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:53:27  来源:igfitidea点击:

Splitting string on certain word into ArrayList - java

javastringsplit

提问by Bipa

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 中。我可以将字符串拆分为" ",但我想将字符串拆分为"farmersmarket"并将其存储到Arraylist. 能够返回索引的字符串之一。

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

有什么想法可以拆分字符串"farmersmarket"吗?

回答by juergen d

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

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

之后您不需要 anArraylist来获取令牌的特定元素。您可以像这样访问每个令牌

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

If you need a Listyou can do

如果你需要一个List你可以做的

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

and if it has to be an Arraylistdo

如果必须Arraylist这样做

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

回答by Vikdor

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.

假设您仍然想在输入字符串没有您要拆分的字符时返回字符串列表,则 Arrays.asList(inputString.split(" ")) 应该可以工作。

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

例如 Arrays.asList("farmersmarket".split(" ")) 将返回一个只包含一个元素——farmersmarket 的列表。