我有一個包含以下文本的字串:
16/2730 99 16/2730 97 16/2730 81 16/2730 76 16/2730 103 16/2730 102 16/2730 101
我想用另一個字符“-”替換單個空格(“”)。我想要的結果是:
16/2730-99 16/2730-97 16/2730-81 16/2730-76 16/2730-103 16/2730-102 16/2730-101
關于如何用另一個字符替換單個空格,同時單獨留下多個空格的任何建議?
uj5u.com熱心網友回復:
除了蒂姆威廉姆斯在評論中的有效提示之外,另一種方法可能是以下方法(假設搜索序列的數字、斜線和單個空格" "可以識別為數字):
- 將字串按空格拆分為一個變體陣列,
- 為僅具有數字右鄰居的元素添加連字符,
- 再次用空格填充 ""-元素并
- 加入陣列,將分隔符設定為
"".
例子
Sub Example()
Dim s As String
s = "16/2730 99 16/2730 97 16/2730 81 16/2730 76 16/2730 103 16/2730 102 16/2730 101"
Dim tmp As Variant
tmp = Split(s)
'Debug.Print Join(tmp, "|") ' optional display in immediate window
'Loop through splitted array elements
Dim i As Long
For i = 0 To UBound(tmp) - 1
If IsNumeric(tmp(i 1)) Then ' if immediate right neighbour is numeric
tmp(i) = tmp(i) & "-" ' .. add a hyphen to the current element
ElseIf tmp(i) = "" Then ' if current element was a blank
' .. give back the former blank values (<~~ Edited ~~>)
tmp(i) = IIf(IsNumeric(Right(tmp(i 1), 1)), " ", " ")
End If
Next i
Debug.Print Join(tmp, "") ' put completed elements together again
End Sub
結果在 VB 編輯器的即時視窗中
16/2730-99 16/2730-97 16/2730-81 16/2730-76 16/2730-103 16/2730-102 16/2730-101
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/380754.html
上一篇:Excel應用程式。輸入完整地址
