Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

reading one word out of a string

 
Nikki Agr
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd go for option two and then use String's substring method.
 
Nikki Agr
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried something like follows and looks like it worked. Thanks for your suggestions. Cheers!

 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, I didn't quite get you. Alternatively, could I trim it?



 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That would work. I meant "new String(cd, 0, i)", but trimming will also work.
 
Nikki Agr
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, got you. Thanks
 
Gerardo Tasistro
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this:

 
Samrat Som
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic