Removal of excess white space

5

How to remove white space within a string ?

It would be to remove spaces from a text string, except for simple spaces between words. Like the "tidy up" function in Excel.

    
asked by anonymous 02.10.2017 / 20:23

2 answers

6

The AllTrim() function resolves most cases. If you want to delete it in the middle:

Function MiddleTrim(cText)
    Local cClean := ""
    Local cLast := " "
    Local nLen := Len(cText)
    Local i
    Local cChar
    For i := 1 To nLen
        cChar := Substr(cText, i, 1)
        If cChar != " "
            cClean += cChar
        ElseIf cLast != " "
            cClean += " "
        EndIf
        cLast := cChar
    Next
    If Substr(cClean, Len(cClean), 1) == " "
        cClean := Substr(cClean, 1, Len(cClean) - 1)
    EndIf
Return cClean

In this way, it reads character by character identifying whether a space already existed before, only copies the character if it is not space or if it is the space immediately following a non-space, that is, only one space remains. As it can get a last space at the end, it cleans too. Going from character to character is what StrTran() and AllTrim() would do, so you have a chance to be more efficient in this way by going only once.

In Harbor perhaps not because it would run in C quite efficiently. I do not know how it is today, but ADVPL had quite inefficient implementation on many things, so much so that some common features in Harbor or even Clipper even recommend avoiding use.

    
02.10.2017 / 21:58
3

An alternative:

Function MiddleTrim(cText)
    While "  " $ cText
        cText = StrTran(cText, "  ", " ")
    End
    Return AllTrim(cText)

Remembering that although shorter than @Maniero's response (which has already received my +1), it is not necessarily more performative, as it can scroll through the string several times.

Points of interest:

  • StrTran(cText, " ", " ") exchange occurrences of two spaces by one. But since the function is not recursive, it needs a loop ;

  • While " " $ cText loop while " " is contained in cText;

  • Finally, AllTrim removes the spaces from the "ends" of the string .

Note:

Based on Harbor syntax, if there is any difference in Advpl, it will probably be just an adjustment in While .. End . What's relevant here is logic.

    
04.10.2017 / 03:38