Page 1 of 1

JoinString() putting the parts together again

Posted: Tue Aug 14, 2007 8:15 pm
by technicorn
Here's the counterpart for SplitString():

Code: Select all

; Companion for SplitString(), joining the parts together,
; can also be used for any string array, not necessarily from SplitString()
;
; sa.s() =    The array that contains the strings to be joind into one
; splitCnt =  Number of strings to join, must be <= number of strings in array
; delimiter = delimiter to put between string parts
;
; Returns the joind string
Procedure.s JoinString(sa.s(1), splitCnt.l, delimiter.c)
  Protected lenSum.l, i.l, saUBound.l = splitCnt - 1
  Protected *sOut.Character, s.s
  
  For i = 0 To saUBound
    lenSum + Len(sa(i)) + 1 ; Add space for delimiter
  Next i

  lenSum - 1  ; Omit delimiter at end of string
  If lenSum <= 0
    ProcedureReturn ""
  EndIf
  
  s = Space(lenSum)
  *sOut = @s
  For i = 0 To saUBound
    lenSum = Len(sa(i))
    If lenSum
      CompilerSelect SizeOf(Character)
        CompilerCase 1
          CopyMemory(@sa(i), *sOut, lenSum) 
          *sOut + lenSum
        CompilerCase 2
          CopyMemory(@sa(i), *sOut, lenSum << 1)
          *sOut + lenSum << 1
        CompilerCase 4
          CopyMemory(@sa(i), *sOut, lenSum << 2)
          *sOut + lenSum << 2
        CompilerDefault
          ; Normally, we should not get here!
          CopyMemory(@sa(i), *sOut, lenSum * SizeOf(Character))
          *sOut + lenSum * SizeOf(Character)
      CompilerEndSelect
    EndIf
    If i < saUBound ; No delimiter after last part
      *sOut\c = delimiter
      *sOut + SizeOf(Character)
    EndIf
  Next i
  
  ProcedureReturn s
EndProcedure
To join this string: "Part1.Part2.Part3.Part4.Part5.Part6.Part7.Part8.Part9.Rest of string"
splitted by SplitString(), it is 3.5 times faster than just using a simple
concatenation of the parts.