arrays - 拆分词再封装,再拆分字符再封装
问题描述
我尝试将单元格 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
解决方案
你可以使用正则表达式
- 将每个字符“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
推荐阅读
- ios - UIPickerView 中的文本字段
- python - 尝试在 Pycharm 中通过 pip 安装 numpy 时出错
- javascript - 从 Forge externalId 转换为 IfcGuid [model-derivative-api]
- reactjs - 如何在 PropTypes 中使用 Redux 的 useSelector 和 useDispatch hooks
- php - 如何将 PDO::FETCH_CLASS 与构造函数带参数的类一起使用?
- node.js - React.js 数据未保存到状态变量
- python - 使用嵌套列表创建字典,其中第一个列表是列,每个列表是一行?
- drone.io - 登录自托管 Drone.io 所需的批准组织
- matlab - 使用带有 fwrite 和下一行的变量
- vue.js - Nuxt 页面方法需要 js 方法