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 first word after a space, but it may not be until the end, it may be before the non-alpha character. How will it be in Java 1.5?

+3
source share
4 answers

You can use regular expressions and a class: Matcher

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
+5
source

You can use String.split :

line.split(" ");

What for the first line will give:

{ "Smith", "John" }

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

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

+4

, .

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

!

+1

Personally, I really like the text tokenizer. I know that it’s not in style these days when the split is so simple and that’s it, but ...

(Psuedocode due to the 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.

+1
source

Source: https://habr.com/ru/post/1748234/


All Articles