如何在visual basic中将整数附加到数组中

时间:2017-03-19 15:02:36

标签: vb.net

我正在创建一个程序,它将没有标点符号的句子作为输入,然后搜索特定单词的出现次数。

 Dim sntnce As String
    Dim srchWord As String
    Dim words As String()
    Dim word As String
    Dim count As Integer
    Dim index As New System.Text.StringBuilder()

    Console.WriteLine("Enter your sentence: ")
    sntnce = Console.ReadLine()
    sntnce = LCase(sntnce)

    Console.WriteLine("Enter the word you want to find the position of: ")
    srchWord = Console.ReadLine()
    srchWord = LCase(srchWord)

    words = sntnce.Split(New Char() {" "c})
    Console.WriteLine(" ")

    For Each word In words
        If word = srchWord Then
            index.Append(count)
            count += 1
        Else
            count += 1
        End If
    Next

    Console.WriteLine("Your word appears in the position(s)...")
    Console.WriteLine(index)
    Console.ReadLine()

for循环获取一个单词的索引(如果在句子中找到)并将其附加到字符串中,但是我想将它附加到数组中,以便索引的值可以单独输出,但是我不能找到任何有用的解决方案。我怎样才能做到这一点?感谢

1 个答案:

答案 0 :(得分:1)

阵列只有固定大小。处理要添加的集合时,请删除或插入使用List(Of T)

我认为您想要的是以下内容:

Sub Main()
    Dim sntnce As String
    Dim srchWord As String
    Dim words As String()
    Dim word As String
    Dim count As Integer

    Console.WriteLine("Enter your sentence: ")
    sntnce = Console.ReadLine()
    sntnce = LCase(sntnce)

    Console.WriteLine("Enter the word you want to find the position of: ")
    srchWord = Console.ReadLine()
    srchWord = LCase(srchWord)

    words = sntnce.Split(New Char() {" "c})
    Console.WriteLine(" ")
    ' Create an expandable list of integers 'index_list'
    Dim index_list As New List(Of Integer)
    For index As Integer = 1 To words.Length
        ' It's recommened to use `Equals()` for string equality instead of `=`
        ' Arrays in VB.NET are 0-based so the i-th elements is located in `list(i-1)`
        If words(index - 1).Equals(srchWord) Then
            ' Add index to list if there is a match
            index_list.Add(index)
        End If
    Next
    ' Create a fixed array of strings to hold the character representation of the integer index array. 
    ' Since I know the size I can use an array instead of a list.
    Dim index_list_string As String() = New String(index_list.Count) {}
    For index As Integer = 1 To index_list.Count
        ' One to one mapping of integer to string
        index_list_string(index - 1) = index_list(index - 1).ToString()
    Next
    Console.WriteLine("Your word appears in the position(s)...")
    ' Take the array of strings and combine it into one string with commas in between using the `.Join()` function
    ' For example `{"A","B","C"} => "A, B, C"
    Console.WriteLine(String.Join(", ", index_list_string))
    Console.ReadLine()
End Sub