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 c开发者_JAVA百科haracter. How would this be in Java 1.5?
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
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?
You will want to use a regular expression like the follwoing.
\s{1}[A-Z-a-z]+
Enjoy!
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.
精彩评论