FindStringReverse()

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
User avatar
Michael Vogel
Addict
Addict
Posts: 2797
Joined: Thu Feb 09, 2006 11:27 pm
Contact:

Re: FindStringReverse()

Post 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.
davido
Addict
Addict
Posts: 1890
Joined: Fri Nov 09, 2012 11:04 pm
Location: Uttoxeter, UK

Re: FindStringReverse()

Post 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
DE AA EB
User avatar
Michael Vogel
Addict
Addict
Posts: 2797
Joined: Thu Feb 09, 2006 11:27 pm
Contact:

Re: FindStringReverse()

Post 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))
davido
Addict
Addict
Posts: 1890
Joined: Fri Nov 09, 2012 11:04 pm
Location: Uttoxeter, UK

Re: FindStringReverse()

Post by davido »

Hi Michael,

Brilliant.

Thank you for all your help.

regards

Dave
DE AA EB
Post Reply