• Post Reply Bookmark Topic Watch Topic
  • New Topic

reading the second word from a string

 
Kondapally Ashwin
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I wanted to write a program where I can read the second word of every line in a file and sort out the lines based on the lexicographic comparison of the second word of each line in the file. Is there any method where I can read the second word in a given line?

Regards,
Ashwin.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's nothing built-in that has "second word" in the description, but there are a bunch of good choices. In rough easy to trickier order ...

StringTokenzier or String.split() can break a line into a bunch of tokens or an array. One of those would be quick & easy if your words always have spaces around them, never quotes or punctuation or anything you don't want to keep.

The Pattern and Matcher classes for regular expressions could be more sophisticated about those punctuation and quote issues. The doc for Pattern has most of what you need to know.

Scanner is a very cool way to read tokens out of a string or stream.

See if one of those looks interesting.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!