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

时间:2019-05-18 01:16:32

标签: arrays excel string nested-loops

我尝试将字符串的每个单词封装在单元格A1中的两个大括号'{''}'之间 然后将每个单词的每个字母/字符封装在方括号'['']'中。
这样的字符串:“苹果很甜”变成:

{[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

2 个答案:

答案 0 :(得分:3)

您可以使用正则表达式

  • 将每个字符'x'替换为[x]
  • { }替换每个字符空间序列
  • 在字符串的开头添加{,在字符串的末尾添加}

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

enter image description here

答案 1 :(得分:2)

您只需要重置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

enter image description here