首页 > 解决方案 > 拆分词再封装,再拆分字符再封装

问题描述

我尝试将单元格 A1 中的字符串的每个单词封装在两个大括号“{”“}”之间,然后将每个单词的每个字母/字符封装在括号“[”“]”内。
所以字符串:“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

标签: arraysexcelstringnested-loops

解决方案


你可以使用正则表达式

  • 将每个字符“x”替换为[x]
  • 将每个字符空间序列替换为{ }
  • 在字符串{的开头和结尾添加 a}

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, "[$1]")
    .Pattern = "(\S)\s+"
    sRes = .Replace(sRes, "$1 } { ")
    sRes = "{ " & Trim(sRes) & " }"
End With
enCapsulate = sRes

End Function

在此处输入图像描述


推荐阅读