简体   繁体   中英

How can I split a String into an Array then return a given element?

I have a string like this: "Name foo Modified bar"

I want to split this string and then return only "foo". I have looked into splitting strings and found this:

String nameString = "Name foo Modified bar";
System.out.println(
    java.util.Arrays.toString(
    nameString.split(" ")
));

Output:

[Name, foo, Modified, bar]

I would like to be able to get "foo" on it's own, as a local variable. Something like this:

String name = output.get(1);

This would work if output was an ArrayList that namestring was split into.

How should I approach getting this result? Should I use the string splitting method I have found or something else? Is there a way to split a string into an arraylist?

Thanks.

In one line:

String name = nameString.split(" ")[1];

In two:

String []tokens = nameString.split(" ");
String name = tokens[1];     

To create an ArrayList:

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

Easiest thing is to grab the element from the array using square bracket notation:

String nameString = "Name foo Modified bar";
String name = nameString.split(" ")[1];

Or, if you particularly want it as a collection:

List<String> nameList = Arrays.asList(nameString.split(" "));
String name = nameList.get(1);

String.split() returns an array.

So

String[] elems = nameString.split(" ");
String result = elems[1];

See the Arrays tutorial for more info.

如果要ArrayList-

new ArrayList<String>( Arrays.asList(nameString.split(" ") ) )

Is there a way to split a string into an arraylist? Yes:

String toFindString="foo";
String nameString = "Name foo Modified bar";
List<String> nameStringList = Arrays.asList(nameString.split(" "));

To find any string from the list.

for (String string : nameStringList) {
        if(string.equals(toFindString)){
                return string;
        }
    }

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