Trim/LTrim/RTrim extension

Share your advanced PureBasic knowledge/code with the community.
User avatar
Lunasole
Addict
Addict
Posts: 1091
Joined: Mon Oct 26, 2015 2:55 am
Location: UA
Contact:

Trim/LTrim/RTrim extension

Post by Lunasole »

I've made about 4 or 5 different variants of those functions in different programs, before finally spent few minutes to make something "unified" :mrgreen:
Result is not much cool (about 5 times slower than original functions), but generally OK. Turning comparisons to case-sensitive might also speed it up.

PS. It would be nice of course if built-in PB functions support not only single-char pattern

Code: Select all

EnableExplicit

; Few extensions to Trim/LTrim/RTrim functions
; String		a string to trim
; Pattern		string to exclude
; RETURN:		modified string
Procedure$ TrimS(string$, pattern$)
	Protected L = Len(pattern$)
	Protected C = @string$
	Protected D = @string$ + StringByteLength(string$) - L * SizeOf(Character)
	While CompareMemoryString(C, @pattern$, #PB_String_NoCase, L) = #PB_String_Equal
		C + L * SizeOf(Character)
	Wend
	While CompareMemoryString(D, @pattern$, #PB_String_NoCase, L) = #PB_String_Equal
		PokeC(D, 0)
		D - L * SizeOf(Character)
	Wend
	ProcedureReturn PeekS(C)
EndProcedure
Procedure$ LTrimS(string$, pattern$)
	Protected L = Len(pattern$)
	Protected C = @string$
	While CompareMemoryString(C, @pattern$, #PB_String_NoCase, L) = #PB_String_Equal
		C + L * SizeOf(Character)
	Wend
	ProcedureReturn PeekS(C)
EndProcedure
Procedure$ RTrimS(string$, pattern$)
	Protected L = Len(pattern$)
	Protected D = @string$ + StringByteLength(string$) - L * SizeOf(Character)
	While CompareMemoryString(D, @pattern$, #PB_String_NoCase, L) = #PB_String_Equal
		PokeC(D, 0)
		D - L * SizeOf(Character)
	Wend
	ProcedureReturn PeekS(@string$)
EndProcedure


; example
Debug "== Source:"
Debug "aaaaaaaaBBBBBBaaaaaaa"
Debug ""

Debug "== Trim (a, aa, aaa, CRLF):"
Debug TrimS("", "a")
Debug TrimS("aaaaaaaaBBBBBBaaaaaaaa", "aa")
Debug TrimS("aaaaaaaaBBBBBBaaaaaaaa", "aaa")
Debug TrimS(#CRLF$ + #CRLF$ + "aaaaaaaaBBBBBBaaaaaaaa" + #CRLF$ + #CRLF$, #CRLF$)

Debug "== LTrim (a, aa, aaa, CRLF):"
Debug LTrimS("aaaaaaaaBBBBBBaaaaaaa", "a")
Debug LTrimS("aaaaaaaaBBBBBBaaaaaaaa", "aa")
Debug LTrimS("aaaaaaaaBBBBBBaaaaaaaa", "aaa")
Debug LTrimS(#CRLF$ + #CRLF$ + "aaaaaaaaBBBBBBaaaaaaaa" + #CRLF$ + #CRLF$, #CRLF$)

Debug "== RTrim (a, aa, aaa, CRLF):"
Debug RTrimS("aaaaaaaaBBBBBBaaaaaaa", "a")
Debug RTrimS("aaaaaaaaBBBBBBaaaaaaaa", "aa")
Debug RTrimS("aaaaaaaaBBBBBBaaaaaaaa", "aaa")
Debug RTrimS(#CRLF$ + #CRLF$ + "aaaaaaaaBBBBBBaaaaaaaa" + #CRLF$ + #CRLF$, #CRLF$)
"W̷i̷s̷h̷i̷n̷g o̷n a s̷t̷a̷r"