Pentium10
Pentium10

Reputation: 207912

How to get the second word from a String?

Take these examples

Smith John
Smith-Crane John
Smith-Crane John-Henry
Smith-Crane John Henry

I would like to get the John The first word after the space, but it might not be until the end, it can be until a non alpha character. How would this be in Java 1.5?

Upvotes: 3

Views: 16780

Answers (4)

Bill K
Bill K

Reputation: 62769

Personally I really like the string tokenizer. I know it's out of style these days with split being so easy and all, but...

(Psuedocode because of high probability of homework)

create new string tokenizer using (" -") as separators
iterate for each token--tell it to return separators as tokens
    if token is " "
        return next token;

done.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838226

You can use regular expressions and the Matcher class:

String s = "Smith-Crane John-Henry";
Pattern pattern = Pattern.compile("\\s([A-Za-z]+)");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
    System.out.println(matcher.group(1));
}

Result:

John

Upvotes: 5

Justin Ethier
Justin Ethier

Reputation: 134167

You could use String.split:

line.split(" ");

Which for the first line would yield:

{ "Smith", "John" }

You could then iterate over the array to find it. You can also use regular expressions as the delimiter if necessary.

Is this good enough, or do you need something more robust?

Upvotes: 5

Doug
Doug

Reputation: 5318

You will want to use a regular expression like the follwoing.

\s{1}[A-Z-a-z]+

Enjoy!

Upvotes: 1

Related Questions