2016-10-13 3 views
0

Как создать программу, которая идентифицирует отдельные слова в предложении и сохранить их в списке? Затем я хочу, чтобы программа создала список позиций для слов в этом списке, за исключением этих списков в виде одного файла.Сохранение списка слов в Visual Basic

Модуль Module1

Sub Main() 
    Dim WordNumber As Integer = 0 
    Dim StartofWord As Integer = 1 
    Dim Text As String = "" 
    Dim L As Integer = 0 
    Dim Word As String 

    Console.WriteLine("Enter your sentence ") 
    Dim LotsofText As String = UCase(Console.ReadLine) 

    Console.WriteLine("Enter your word") 
    Word = UCase(Console.ReadLine()) 


    If Mid(LotsofText, Len(LotsofText) - 1, 1) <> " " Then LotsofText = LotsofText + " " 


    For L = 1 To LotsofText.Length 
     If (Mid(LotsofText, L, 1)) = " " Then 
      WordNumber = WordNumber + 1 
      Text = (Mid(LotsofText, StartofWord, L - StartofWord)) 
      'Console.WriteLine(Text) 
      StartofWord = L + 1 

      If Text = Word Then 
       Console.WriteLine(WordNumber) 

      End If 


     End If 

    Next 


    If Not Text = Word Then 
     Console.WriteLine("Error word not found") 

    End If 


    Console.Write("Press Enter to Exit") 
    Console.ReadLine() 


End Sub 

End Module

+0

Думайте, что вы, возможно, ищете Linq. Посмотрите на http://stackoverflow.com/questions/9645326/how-to-get-distinct-values-from-listof-t-using-linq – Bugs

+1

Что определяет «Слово» в вашем контексте? Если это просто, что он разделен пробелами, вы можете использовать 'String.Split' для получения массива слов – simonalexander2005

ответ

0

Split ваше предложение по пустому " ", перебирает все слова и добавить позицию в список, если текущее слово соответствует искомому слову.

Dim Sentence = "Hello from the other side and hello from hell" 
Dim SearchWord = "Hello" 

If Not String.IsNullOrWhiteSpace(Sentence) Then 
    SearchWord = SearchWord.Trim 
    Sentence = Sentence.Trim 
    Dim words = Sentence.Split(" ") 
    If Not words.Contains(SearchWord) Then Return 

    Dim searchWordPositions = New List(Of Integer) 
    For i = 0 To words.Length - 1 
     If words(i).Equals(SearchWord, StringComparison.InvariantCultureIgnoreCase) Then 
      searchWordPositions.Add(i) 
     End If 
    Next 
    Console.WriteLine(String.Concat("Found '", SearchWord, "' at Positions: ", String.Join(", ", searchWordPositions))) 
End If 

'Output: 
Found 'Hello' at Positions: 0, 6 

Вместо Console.WriteLine пишите его в файл.