udfItemListCsvReplaceV2
str udfItemListCsvReplaceV2 (str, int, str, str)
;------------------------------------------------------------------------------------------------------------------------------------------
#DefineFunction udfItemListCsvReplaceV2 (strItem, intIndex, strList, strDelimiter)
If strList == "" Then Return strList
strPattern = `"*,*"`
intPos = 0
strSurrogate = Num2Char (7)
While @TRUE
   intPos = StrIndexWild (strList, strPattern, intPos)
   If !intPos Then Break
   strItemWild = StrSubWild (strList, strPattern, intPos)
   strItemTemp = StrReplace (strItemWild, ",", strSurrogate)
   strList = StrReplace (strList, strItemWild, strItemTemp)
   intPos = intPos + StrLen (strItemTemp)
EndWhile
strList = ItemReplace (strItem, intIndex, strList, strDelimiter)
strList = StrReplace (strList, strSurrogate, strDelimiter) ; Recreate list.
Return strList
;..........................................................................................................................................
; This UDF "udfItemListCsvReplaceV2" replaces an item in a list with a new item.
; It returns a new list, with the specified replacement made; the original list is unchanged.
; For example, specifying an index of 1 causes the first item in the list to be replaced with the new item.
; Using -1 as the index will replace the last item in the list.
;
; Note:
; The original list must have no embedded ASCII 7 (Bell) character.
; A null list ("") is not a valid list.
;
; (c)Detlev Dalitz.20120108.
;..........................................................................................................................................
#EndFunction
;------------------------------------------------------------------------------------------------------------------------------------------


; Test.

strCsvLineIn = `1,"lastname,firstname",3,4,,"some other words",7`

; Test 1.
strCsvLineOut = udfItemListCsvReplaceV2 (`"test item 3"`, 3, strCsvLineIn, ",") ; Change item at position 3.

strMsgTitle = "udfItemListCsvReplaceV2|Test.1|Replace item 3"
strMsgText = "strCsvLineIn = " : @LF : strCsvLineIn : @LF : @LF : "strCsvLineOut = " : @LF : strCsvLineOut
Pause (strMsgTitle, strMsgText)


; Test 2.
strCsvLineOut = udfItemListCsvReplaceV2 (`"test last item"`, -1, strCsvLineIn, ",") ; Change item at last position.

strMsgTitle = "udfItemListCsvReplaceV2|Test.2|Replace last item"
strMsgText = "strCsvLineIn = " : @LF : strCsvLineIn : @LF : @LF : "strCsvLineOut = " : @LF : strCsvLineOut
Pause (strMsgTitle, strMsgText)


; Test 3.
strCsvLineIn = ""
strCsvLineOut = udfItemListCsvReplaceV2 (`"test last item"`, -1, strCsvLineIn, ",") ; Change item at last position.

strMsgTitle = "udfItemListCsvReplaceV2|Test.3|Null list"
strMsgText = "strCsvLineIn = " : @LF : strCsvLineIn : @LF : @LF : "strCsvLineOut = " : @LF : strCsvLineOut
Pause (strMsgTitle, strMsgText)

:CANCEL
Exit