拆分单词然后封装,再拆分字符再封装

Split words then encapsulate, then split characters and encapsulate

我尝试将单元格 A1 中字符串的每个单词封装在两个花括号 '{' '}' 之间 然后将每个单词的每个 letter/character 封装在方括号 '[' ']' 中。
所以字符串:"apples are sweet" 变成:

{ [a][p][p][l][e][s] } { [a][r][e] } { [s][w][e][e][ t] }

结果是在下一个单词中重复每个大括号单词:

{ [a][p][p][l][e][s] } { [a][p][p][l][e][s][a][r][e] } { [a][p][p][l][e][s][a][r][e][s][w][e][e][t]}

粗体部分不应该出现。 结果显示在B2.

Sub splitEncapsulate()

    Dim myString As String
    Dim intoStrArr() As String
    Dim i As Integer
    Dim myWord As String

    myString = ActiveSheet.Range("A1").Value
    'splits the string based on the delimeter space
    intoStrArr = Split(myString, " ")
    myWord = ""

    'loops through the string
    For i = LBound(intoStrArr) To UBound(intoStrArr)

        myWord = intoStrArr(i)

        'loop each character in myWord
         For j = 1 To Len(myWord)
             'encapsulate each character with '[ ]'
             char = "[" & Mid(myWord, j, 1) & "]"

             'group characters again
              joinedChars = joinedChars & char

         Next j

        'encapsulate each word with '{ }' and add space in between words
        newtxt = newtxt + "{ " + joinedChars + " }" + " "

    Next i
    ActiveSheet.Range("A1").Offset(0, 1).Value = newtxt
End Sub

您只需要重置 joinedChars,与每个循环一样,它目前保持不变:

之后
newtxt = newtxt + "{ " + joinedChars + " }" + " "

添加

joinedChars = ""

(使用 F8 单步执行代码有很大帮助。这让你可以看到每一行单独触发,所以在第二个循环中,我在第一次使用 joinedChars 它已经保存了 apples 数据,所以你需要在再次使用它之前清除它)。

编辑:仅供参考,如果您想在任何单元格上快速使用它,您也可以将其设为一个函数。在工作簿模块中添加以下内容:

Function splitEncapsulate(cel As Range)

' Enter the code here, with my suggestion above
' but replace `ActiveSheet.Range("A1").Offset(0, 1).Value = newtxt` with the next line:
splitEncapsulate = Trim(newtxt)
End Function

您可以使用正则表达式

  • 将每个字符 'x' 替换为 [x]
  • 将每个 character-space 序列替换为 { }
  • 在字符串的开头添加一个{,在字符串的结尾添加一个}

Option Explicit
Function enCapsulate(str As String)
    Dim sRes As String
    Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
With RE
    .Pattern = "(\S)"
    .Global = True
    sRes = .Replace(str, "[]")
    .Pattern = "(\S)\s+"
    sRes = .Replace(sRes, " } { ")
    sRes = "{ " & Trim(sRes) & " }"
End With
enCapsulate = sRes

End Function