aspose file tools*
The moose likes Beginning Java and the fly likes reading one word out of a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "reading one word out of a string" Watch "reading one word out of a string" New topic
Author

reading one word out of a string

Nikki Agr
Greenhorn

Joined: Nov 09, 2008
Posts: 13
Hi everyone,
Suppose I have a string "The brown fox jumped" and I want to read the word, which starts at index 4. How do I go about it? Thanks in advance.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

There are (at least) two strategies you could use to do this:

1) Starting at index 4, read each character in the String, copying it to a new character sequence, until you get to a space

2) Look for the first index of a space after the 4th index, then copy the sub string from index 4 to the next space into a new String

You should look at the String API for methods that should help you out.


Steve
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19790
    
  20

I'd go for option two and then use String's substring method.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Nikki Agr
Greenhorn

Joined: Nov 09, 2008
Posts: 13
I tried something like follows and looks like it worked. Thanks for your suggestions. Cheers!

Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19790
    
  20

There's one problem with that code: the string will have 11 (16 - 5) null-characters ('\0') at its end. There is a quick fix: use the other String constructor that takes a char[]. Hint: you already have the count as one of your variables.
Nikki Agr
Greenhorn

Joined: Nov 09, 2008
Posts: 13
Sorry, I didn't quite get you. Alternatively, could I trim it?



Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19790
    
  20

That would work. I meant "new String(cd, 0, i)", but trimming will also work.
Nikki Agr
Greenhorn

Joined: Nov 09, 2008
Posts: 13
Okay, got you. Thanks
Gerardo Tasistro
Ranch Hand

Joined: Feb 08, 2005
Posts: 362
Try this:

Samrat Som
Ranch Hand

Joined: Feb 04, 2009
Posts: 40
we can also use split function to achieve it ...moreover the inddex 4 means in the question as the second word......in that case we can split the string with " " as the parameter , and then the second word will do.....


SCJP 1.6
SCWCD 1.5 (Preparing...)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: reading one word out of a string