Thursday, July 30, 2009

How do I find the last word in a sentence using visual basic.? I have an example?

I have tried and tried to figure this out, but i cannot come up with anything. Bare with me, Im new to visual basic.





But here it goes. Example:





The cow eats good food.





I want to find and display the word "food" somewhere else (txtbox, listbox, the list goes on, but you get the point.) How do i got about finding the last word? The one i found to have a result was





lastword = sentence.indexof "." - lastIndexOf " "





but all i got was number that i couldnt figure out how to use. Everything else just wont let the program start, or it crashes. Any ideas?

How do I find the last word in a sentence using visual basic.? I have an example?
The two 'IndexOf' statements return the positions of the period and the last space, respectively.





What you want is the substring between those positions, like this:





space = sentence.lastindexof(" ")


end = sentence.lastindexof(".")


lastword = sentence.mid(space, end - space)





I'm not sure, but I think the second parameter of the MID function is the number of character you want from the string, and not the position of the last character, that's why I subttracted the space from the end.





(MID may also be called substring, depending on the basic you use.)
Reply:hi, use .substring() method to extract the word by using the number u got from indexof. Or you can use the split method by referring to the link I posted.
Reply:I am not in sure about VB.net but I for VB6 you can run through each and every character of the sentence (starting at the end) and looking for the first space, once you have the location of the first space you can use the right$ command to get the last word.





i.e.





For intI = Len(strSentence) To 1 Step -1


strA = mid$(strSentence, intI, 1)


if (strA = " ") Then


strLastWord = Right$(strSentence, intI - 1)


Exit For


End If


Next intI


No comments:

Post a Comment