Page 2 of 2

Re: FindStringReverse()

Posted: Wed Dec 26, 2012 10:07 pm
by Michael Vogel
Davido, is there any reason for reversing the string? Even it does not take a lot of time, if does take some. If you have to detect the rightmost occurence of a substring, the efforts for reversing the string should be avoided.

Re: FindStringReverse()

Posted: Thu Dec 27, 2012 8:48 pm
by davido
Dear Michael,

Thank you for taking the time to look at my problem.

What I am trying to do is to locate the position of the last occurrence of a character in the string. Unfortunately there may be more than one occurrence of that character in the string.

The only way I could think of was to reverse the string find the first occurrence of the character and then use simple arithmetic to find it's location in the original string.

Do you infer that there is a way to locate the position of the character by other means?

Regards

Dave

Re: FindStringReverse()

Posted: Fri Dec 28, 2012 10:11 am
by Michael Vogel
I think, the only reason for the "speed" of your ReverseString solution is, that calling internal commands is quicker than using own procedures. Otherwise, Skywalk's solution should be faster because it does not need to swap memory to reverse the string.

If you need to search only for a single character, I would think about another approach:

Code: Select all

#Iter=1000000
#Len=1000

Procedure FindChar(a.s,c.a)

	Protected l=Len(a);    using a global variable for 'l' would speed up the procedure

	While l
		l-1
		If PeekA(@a+l)=c
			ProcedureReturn l
		EndIf
	Wend

	ProcedureReturn 0

EndProcedure

A$=RSet("Hello K WorKld",#Len,"_")

Dt=ElapsedMilliseconds()
For M=1 To #Iter
	result=FindString(ReverseString(A$),"K")
Next M
Dt-ElapsedMilliseconds()

MessageRequester("'Reverse' Time: "+Str(M-1)+" iterations:",Str(-Dt)+" ms"+#CR$+"Result: "+Str(result))

Dt=ElapsedMilliseconds()
For M=1 To #Iter
	result=FindChar(A$,'K')
Next M
Dt-ElapsedMilliseconds()

MessageRequester("Procedure Time: "+Str(M-1)+" iterations:",Str(-Dt)+" ms"+#CR$+"Result: "+Str(result))

Dt=ElapsedMilliseconds()
For M=1 To #Iter
	
	result=Len(A$)

	While result
		result-1
		If PeekA(@A$+result)='K'
			Break
		EndIf
	Wend

Next M
Dt-ElapsedMilliseconds()

MessageRequester("'Inline' Time: "+Str(M-1)+" iterations:",Str(-Dt)+" ms"+#CR$+"Result: "+Str(result))

Re: FindStringReverse()

Posted: Fri Dec 28, 2012 3:08 pm
by davido
Hi Michael,

Brilliant.

Thank you for all your help.

regards

Dave