Page 2 of 2

Re: Special chars in strings

Posted: Mon Feb 09, 2015 5:22 pm
by davido
@Danilo
Nice escape function.
Thank you for sharing. :D

Re: Special chars in strings

Posted: Tue Feb 10, 2015 8:47 am
by Shield
Apart from the fact that the substitution happens at runtime and, even though the code is short and concise it is also highly inefficient. :wink:

The "right" solution would be to have something like this natively implemented using a string prefex, e.g.

Code: Select all

Define a.s = &"Hello\nWorld"
That way existing code is unaffected and substitution is only done if explicitly stated.

Re: Special chars in strings

Posted: Tue Feb 10, 2015 10:39 am
by Danilo

Re: Special chars in strings

Posted: Tue Feb 10, 2015 11:01 pm
by Shield
:wink:

This is what I've come up with. I didn't do any speed testing or serious unit testing,
so I'd be happy if somebody could give me a hand. :P
  1. The main "issue" with Danilo's procedure is that it iterates through the same string multiple times.
  2. I put the replacement logic into a separate procedure in order to speed up cases
    where no escape sequences occur.
  3. I'm not sure if putting a #NUL character into the middle of a string confuses PB,
    but it seems to work so far (possible memory leak?).
  4. The Select statement could be optimized by removing it entirely and replacing
    the insertion character assignment with a lookup table. I don't believe PB's selects actually work that way (I could be wrong).
    In other languages this would be the normal way how select works.

Code: Select all


EnableExplicit

Procedure.i EscapeMove(*current.Character)
	Protected *insert.Character
	
	*insert = *current
	While *current\c <> #NUL
		If *current\c = '~'
			*current + SizeOf(Character)
			Select *current\c
				Case '~' : *current\c = '~'
				Case 'q' : *current\c = '"'
				Case 'n' : *current\c = #LF
				Case 'r' : *current\c = #CR
				Case 't' : *current\c = #TAB
				Case 'v' : *current\c = #VT
				Case '0' : *current\c = #NUL
				Case 'a' : *current\c = #BEL
				Case 'b' : *current\c = #BS
				Case 'f' : *current\c = #FF
				Case #NUL : Break
			EndSelect
		EndIf
		
		*insert\c = *current\c
		*current + SizeOf(Character)
		*insert + SizeOf(Character)
	Wend
	*insert\c = #NUL
	
	ProcedureReturn *current
EndProcedure

Procedure.i EscapeInline(*current.Character)
	While *current\c <> #NUL
		If *current\c = '~'
			ProcedureReturn EscapeMove(*current)
		EndIf
		*current + SizeOf(Character)
	Wend
	
	ProcedureReturn *current
EndProcedure

Procedure.s Escape(string.s)
	EscapeInline(@string)
	ProcedureReturn string
EndProcedure

Debug Escape("Hello~qWorld~q~tWhat's Up?~nNext Line")
Edit: fixed small bug.

Re: Special chars in strings

Posted: Wed Feb 11, 2015 12:51 am
by Little John
And let's not forget mk-soft's sprintf like function:
http://www.purebasic.fr/english/viewtop ... 12&t=32026