Join String Array Elements into a Single String

Category: Arrays

Date: 02-16-2022

Return to Index


 
'The JOIN$ statements combines array elements into a single string
'separated by specified delimiter of one or more characters.
'The PARSE statement is a complementary function used to separate
'a string into an array.
 
'Primary Code:
'Syntax:   A$ = JOIN$(array(), {delim$ | BINARY})
Dim MyArray(5) As String, a$
Array Assign MyArray() = "1", "5", "3", "6", "2", "8"
a$ = Join$(MyArray(),"")     'a$ now contains "153628"
a$ = Join$(MyArray(),":")    'a$ now contains "1:5:3:6:2:8"
a$ = Join$(MyArray(),"..")   'a$ now contains "1..5..3..6..2..8"
a$ = Join$(MyArray(),$crlf)  'creates a multi-line result
 
delimiter$ = $dq+$dq + $chr(46) + $dq+$dq
'This is a special delimiter recognized by PowerBASIC to help creation of CSV files
a$ = Join$(MyArray(),$delimiter) 'joins elements as CSV (can be read by Excel)
 
 
'Compilable Example:  (Jose Includes)
'This example shows how to use the JOIN$ to allow writing an entire array
'into a file with a single PUT statement, then reads the array back.
#Compiler PBWin 9, PBWin 10
#Compile EXE
#Dim All
%Unicode=1
#Include "Win32API.inc"
Global hDlg As Dword
 
Function PBMain() As Long
   Dialog New Pixels, 0, "Test Code",300,300,200,200, %WS_OverlappedWindow To hDlg
   Control Add Button, hDlg, 100,"Join and Save to File", 40,10,120,20
   Control Add Button, hDlg, 200,"Get Array From File", 40,40,120,20
   Dialog Show Modal hDlg Call DlgProc
End Function
 
CallBack Function DlgProc() As Long
   Dim MyArray(5) As String, a$
   If CB.Msg = %WM_Command AND CB.Ctl = 100 AND CB.Ctlmsg = %BN_Clicked Then
      Array Assign MyArray() = "1", "5", "3", "6", "2", "8"
      a$ = Join$(MyArray(),":")     'a$ now contains "1:5:3:6:2:8"
      If IsFile("myfile.txt") Then Kill "myfile.txt"   'remove file, if it exists
      Open "myfile.txtFor Binary As #1
      Put #1,1, a$    'put entire array into file with a single statement
      Close #1
      MsgBox "Joined with " + $dq + ":" + $dq + " and saved as: " + a$
   End If
   If CB.Msg = %WM_Command AND CB.Ctl = 200 AND CB.Ctlmsg = %BN_Clicked Then
      Open "myfile.txtFor Binary As #1
      Get$ #1, Lof(1), a$    'put entire array into file with a single statement
      Close #1
      Parse a$, MyArray(), ":"
      MsgBox "Retrieved: " + Join$(MyArray()," ")     'a$ now contains "1:5:3:6:2:8"
   End If
End Function
 
'gbs_00068
'Date: 03-10-2012


created by gbSnippets
http://www.garybeene.com/sw/gbsnippets.htm