【问题标题】:Reading an unknown string from a Text Box从文本框中读取未知字符串
【发布时间】:2012-08-15 07:26:32
【问题描述】:

我有一个文本框,可用作控制台(在表单应用程序中)。

我想在用户输入时运行某个 sub:

broadcast blabla

子会广播字符串blabla。 程序如何只识别第一个单词?

这样的东西有用吗?

If ConsoleInput.Text = "broadcast " & command Then
BroadcastMessage(command)
End If

【问题讨论】:

    标签: vb.net string textbox console word


    【解决方案1】:

    你可以使用String.Split:

    Dim words As String() = ConsoleInput.Text.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
    If words.Length > 1 AndAlso words(0).ToLower() = "broadcast" Then
        BroadcastMessage(words(1))
    End If
    

    编辑:如果您想广播所有单词,最好使用String.Substring

    Dim spaceIndex = ConsoleInput.Text.IndexOf(" "c)
    If spaceIndex > -1 Then
        Dim firstWord = ConsoleInput.Text.Substring(0, spaceIndex)
        If firstWord.ToLower = "broadcast" Then
            broadcast(ConsoleInput.Text.Substring(spaceIndex + 1))
        End If
    End If
    

    【讨论】:

    • 效果很好!但是我该怎么做才能找到接下来的 2 个单词呢?例如:广播'ip''消息'
    • @Antonios:然后使用我的第一个方法将字符串拆分为单独的单词。您可以通过索引器访问这些单词,因为它是 String-Array。例如:Dim word2=words(1)
    • 好的!所以在那种情况下,如果我想将几个单词作为一个字符串,我必须在“引号”之间输入它,对吧?
    • 您的要求在不断变化;)然后您可以改用Regex.Split,例如使用正则表达式here
    • 其实Regex.Split是如何将一个字符串拆分成多个的呢?
    猜你喜欢
    • 1970-01-01
    • 2012-02-28
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 2020-04-10
    • 2012-05-28
    相关资源
    最近更新 更多