繁体   English   中英

VBA - 仅将字符串中的单个空格 (" ") 替换为字符

[英]VBA - Replace only a single whitespace (" ") in a string with a character

我有一个带有以下文本的字符串:

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

关于如何用另一个字符替换单个空格,同时保留多个空格的任何建议?

除了 Tim Williams 在评论中的有效提示之外,另一种方法可能是以下方法(假设搜索数字、斜杠和单个空格" "的序列可以识别为数字)

  • 将字符串按空格拆分为变体数组,
  • 仅向具有数字右邻居的元素添加连字符,
  • 再次用空白填充“”元素,然后
  • 加入将分隔符设置为""的数组。

例子

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
            tmp(i) = " "                         ' .. give it back its former value
        End If
    Next i
    Debug.Print Join(tmp, "")                    ' put completed elements together again

End Sub

结果在 VB 编辑器的即时 window

16/2730-99 16/2730-97 16/2730-81 16/2730-76 16/2730-103 16/2730-102 16/2730-101

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM