【问题标题】:Visual Basic counting positions of a substring within a stringVisual Basic 计算字符串中子字符串的位置
【发布时间】:2016-09-29 17:18:38
【问题描述】:

所以我正在尝试使用 Visual Basic 在 Visual Studio 中创建一个 Windows 窗体应用程序,该应用程序有一个文本框供您输入句子,另一个文本框供您输入该句子中的单词,然后是一个按钮点击句子中输入的单词的位置被输出到标签上。目前,代码计算一个单词的出现次数,但我想对其进行调整,以便计算单词出现的位置(例如,在“Hello hello hello”中输入“hello”并输出 1 2 3。

当前代码低于任何帮助将不胜感激。

Public Class Form1
    'first attempt not working
    Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
        Dim input As String = textBox1.Text
        Dim word As String = textBox2.Text
        Dim occurrences As Integer = 0

        Dim intCursor As Integer = 0
        Do Until intCursor >= input.Length
            Dim strCheckThisString As String = Mid(LCase(input), intCursor + 1, (Len(input) - intCursor))

            Dim intPlaceOfWord As Integer = In-Str(strCheckThisString, word)
            If intPlaceOfWord > 0 Then
                occurrences += 1
                intCursor += (intPlaceOfWord + Len(word) - 1)
            Else
                intCursor = input.Length
            End If
        Loop
        Positions.text = occurrences
    End Sub
End Class

【问题讨论】:

标签: vb.net string substring counting basic


【解决方案1】:

如果单词总是用空格分隔,你可以先将字符串拆分成单词数组

Dim positions = New List(Of Integer)()
Dim words As String() = input.Split()
For i As Integer = 0 To words.Length - 1
    If words(i).ToLower() = "hello" Then
        positions.Add(i + 1)
    End If
Next

现在列表positions 包含句子中问候词的位置。

String.Split method 具有重载,允许您指定其他分隔符,例如逗号。还有一个选项可以删除空条目。

【讨论】:

  • 所以我尝试从这里调整我的代码,但我不断收到消息 System.Collections.Generic.List'1(System.Int32) 出现在我的标签上应该输出位置的位置。知道为什么吗?
  • Public Class Form1 Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
  • Dim input As String = textBox1.Text Dim word As String = textBox2.Text Dim positionword = New List(Of Integer)() Dim words As String() = input.Split() For i As Integer = 0 To words.Length - 1 If words(i).ToLower() = textBox2.Text Then positionword.Add(i + 1) End If Next Positions.Text = positionword.ToString End Sub End Class
  • positionsword 是一个列表,它的 To|String 方法只输出它的类型名称。您必须使用String.Join 才能将列表的内容转换为字符串。
猜你喜欢
  • 2023-04-06
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 2021-01-24
  • 2017-10-20
相关资源
最近更新 更多