我正在制作一个程序,该程序将没有标点符号的句子作为输入,然后搜索特定单词出现的次数。
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 循环会获取单词的索引并将其附加到字符串中,但我想将其附加到数组中,以便可以单独输出索引的值,但是我找不到任何解决方案这种帮助。我怎样才能做到这一点?谢谢
数组只有固定大小。处理要添加、删除或插入的集合时,请使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句