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.
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.
Enjoy your time here.
Ping & DNS - updated with new look and Ping home screen widget
Joined: Feb 26, 2006
Please can i keep this name. This is my nickname and almost all my friends call me the same.
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...
Joined: Jan 30, 2000
["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 ]