【问题标题】:Splitting string with search phrases使用搜索短语拆分字符串
【发布时间】:2020-01-27 03:19:36
【问题描述】:

我想拆分这个字符串:

large "red pill"

进入这个子字符串数组:

arr(0) = "large"
arr(1) = "red pill"

我怎样才能轻松做到这一点?

【问题讨论】:

  • 告诉我当你将字符串分配给代码中的变量时的样子。
  • 你所问的不一定是微不足道的。您实质上要问的是“我如何在副词上拆分字符串”。一种解决方案是提前知道副词,但这样你就将自己限制在副词集合中的值。或者,您需要创建一个解析器来解析英语句子,这可能非常困难,因为英语语言的所有变化(例如,它不是一种正式的语言)。
  • @David 你是说形容词吗? red 和 large 都是形容词。
  • @Mary - 可能是这样,我在高中时英语不及格(两次)。

标签: arrays string vb.net


【解决方案1】:

在您的特定情况下,您可以用双引号分隔

Dim quotes As Char() = { """"c }
Dim text As String = "large ""red pill"""

Dim phrases As String() = text.
    Split(quotes, StringSplitOptions.RemoveEmptyEntries).
    Select(Function(phrase) phrase.Trim()).
    ToArray()

Dim output As String = String.Join(Environment.NewLine, phrases)
Console.WriteLine (output)

' Output:
' [0] - large
' [1] - red pill

对于字符串可以包含多个用空格分隔的“单个单词”的情况,您可以先用双引号分隔,然后用空格分隔并将所有短语组合成一个数组

Dim quotes As Char() = { """"c }
Dim spaces As Char() = { " "c }   
Dim text As String = "large ""red pill"" small medium ""yellow stone"""

Dim result = text.Split(quotes, StringSplitOptions.None).
    SelectMany(Function(phrase, index)
        If index Mod 2 = 0 Then           
            Return phrase.Split(spaces, StringSplitOptions.RemoveEmptyEntries)            
        Else
            Return { phrase }
        End If
    End Function)

Dim output As String = String.Join(Environment.NewLine, result)
Console.WriteLine (output)

' Output:
' [0] - large
' [1] - red pill
' [2] - small
' [3] - medium
' [4] - yellow stone

【讨论】:

    【解决方案2】:

    我刚刚做了这个快速而肮脏的解决方案,它可以很好地满足我的目的

    Dim List As New ArrayList
    Dim Idx, Idx2 As Integer
    
    Do
        Idx = str.IndexOf("""")
        If Idx >= 0 And str.Length > Idx + 1 Then
            Idx2 = str.IndexOf("""", Idx + 1)
            If Idx2 > 0 Then
               List.Add(str.Substring(Idx + 1, Idx2 - Idx - 1).Trim)
               str = str.Remove(Idx, Idx2 - Idx + 1)
            End If
        End If
    Loop Until Idx = -1
    
    For Each w As String In str.Split(" ")
        If w.Trim <> "" Then
            List.Add(w.Trim)
        End If
    Next
    

    【讨论】:

    • 新代码中没有 ArrayList。使用列表(T)。在这种情况下 List(Of String)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2015-12-25
    • 2013-04-02
    • 1970-01-01
    • 2011-12-18
    相关资源
    最近更新 更多