MS访问查询中的修剪字符串

时间:2018-12-27 02:36:06

标签: ms-access

请帮助我解决以下查询。

我想修剪字符串之间的空格。我有一个名为Name的列,它之间有空格。例如,在数据源中,名称格式为“ John Steve Miller”(两者之间有多个空格),我想将其修饰为“ John Steve Miller”(仅一个空格)。预先感谢您

1 个答案:

答案 0 :(得分:1)

Whilst you could use the Replace function to replace every pair of two spaces with a single space:

?Replace("John  Steve Miller", "  ", " ")
John Steve Miller

This will not account for instances in which you have more than two consecutive spaces, e.g.:

?Replace("John   Steve Miller", "  ", " ")
John  Steve Miller
?Replace("John    Steve Miller", "  ", " ")
John  Steve Miller

As such, I would suggest the following function to handle any number of consecutive spaces:

Function TrimSpace(strStr As String) As String
    Dim strRtn As String: strRtn = Replace(strStr, "  ", " ")
    If strRtn = strStr Then
        TrimSpace = Trim(strRtn)
    Else
        TrimSpace = TrimSpace(strRtn)
    End If
End Function
?TrimSpace("John  Steve Miller")
John Steve Miller
?TrimSpace("John   Steve  Miller")
John Steve Miller
?TrimSpace("John    Steve   Miller")
John Steve Miller
?TrimSpace("John     Steve    Miller")
John Steve Miller