How do I get the second word from a string?

Take these examples

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

I want the first word after John's space, but it may be until the end, it may be until non - alphabetic characters How will this work in Java 1.5?

Solution

You can use regular expressions and matcher classes:

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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>