1

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.

3
  • 2
    is what you want always going to be the 2nd element? Or always going to be "foo"? Commented Jul 19, 2012 at 15:51
  • 1
    @Sean Kelly - array indexing is "Java 101" stuff. I recommend that you take the time to do the Java tutorial, or read an introduction to Java programming book. Commented Jul 19, 2012 at 16:02
  • @StephenC Whilst true, I was getting confused with where the output was going to rather than the index. As demonstrated by the fact that I had code which would retrieve a given index from an ArrayList. Commented Jul 23, 2012 at 15:16

5 Answers 5

5

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));
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

String.split() returns an array.

So

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

See the Arrays tutorial for more info.

1 Comment

Thanks but I think Doug Ramsey's answer is more concise.
0

if you want ArrayList -

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

Comments

0

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

1 Comment

I don't think Arrays.asList() has to return an ArrayList (though it probably does). Can't you just keep it as a List<String> and lose the cast?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.