Hello people. I want to find distance between words present in a sentence.the words and sentence are given as input and the distance(no.of words between) should be the output. Say this is a sentence "Hello iam doing fine how about you and how is life?" and my input of words is "iam" and "life" it should give ouput as 8(the no.if words inbetween).here input can be given many words also.
Code in Binaries...
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
posted
0
Are you familiar with the String class? Have you seen the documentation for the indexOf() method?
"I'm not back." - Bill Harding, Twister
Sam Codean
Ranch Hand
Joined: Feb 26, 2006
Posts: 194
posted
0
Use indexOf() method to get the indices of the two words, If both are present then you will have two non-negative numbers. Now 1. From the least of the above indices keep finding spaces using the same metohd overloaded to take start index. 2. Get a Substring from the earlier string starting from least index and ending at the greater index. Split this string and the length of tihs array will be one greater than the number of words in between. Hope that helps!!
On your way in you may have missed that we have a policy on screen names here at JavaRanch. Basically, it must consist of a first name, a space, and a last name, and not be obviously fictitious. Since yours does not conform with it, please take a moment to change it, which you can do right here.
Please can i keep this name. This is my nickname and almost all my friends call me the same.
pascal betz
Ranch Hand
Joined: Jun 19, 2001
Posts: 547
posted
0
since you are looking for the "distance in words":
perhaps you can check out the documentation of String.split()
split your sentence into words, loop the array until you find the first word, then continue until you find your second words. distance = index word one - index word two (plus minus one :-) arrays are 0 indexed).
you would also need to check the cases where only one or none of the words are in the sentence...
pascal
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
posted
0
["codean"]: Please can i keep this name.
Sorry, but no. Not for your display name here, anyway. We're looking for something more like "Sameer Kotian".
[pascal]: since you are looking for the "distance in words":
Oops, I didn't read the problem closely enough here. [ March 05, 2006: Message edited by: Jim Yingst ]