user6740647 user6740647 - 3 months ago 13
Vb.net Question

How can I remove the repeated lines in my output?

If ArrySentence.Contains(InputString) Then
Dim index As Integer = Array.IndexOf(ArrySentence, InputString)

Do Until a >= ArrySentence.GetUpperBound(0) + 1
Dim position As Integer = index + 1
index = Array.IndexOf(ArrySentence, InputString, position)

Console.WriteLine("The word ""{0}"" is at position {1}.", InputString, position)
a = a + 1
Loop


I'm making program that analyses a sentence that contains several words. When a word in that sentence is input, the program identifies all of the positions where the word occurs in the sentence.

It's almost done but the problem is the output repeats some of the lines like:

Please enter a sentence

The apple fall from the apple tree

Please enter a word from the sentence

apple

The word apple is at position 2
The word apple is at position 6
The word apple is at position 2
The word apple is at position 6


Help!

Answer

I do not really understand the reasoning behind your loops. What you want to do is the following: Search for the word in the array. If it exists, print its position. Otherwise exit. Start over.

Here is how I would do it:

Dim index As Integer = Array.IndexOf(ArrySentence, InputString)
While index >= 0 'while the word has been found
    'Output the occurrence
    Console.WriteLine("The word ""{0}"" is at position {1}.", InputString, index + 1)
    'Search for the next occurrence
    index = Array.IndexOf(ArrySentence, InputString, index + 1)
End While
Comments