Iterating a string

BlitzMax Forums/BlitzMax Programming/Iterating a string

SpectreNectar(Posted 2012) [#1]
Hi,

how would one make a loop that goes through the chars of a string one at a time?

Something like this?
for local s$ = eachin(str)
if(s="a") then 
print "oregano"
endif
next


Only this wont work...


SpectreNectar(Posted 2012) [#2]
Oh how could I forget! ...the bracket indexer []

For Local s% = 0 Until str.length
If(str[s..(s+1)]="a") Then 
Print "oregano"
EndIf
Next



Jesse(Posted 2012) [#3]
or
For Local i = 0 Until s.length
	If s[i]="a"[0] Then 
		Print "oregano"
	EndIf
next


its a bit faster than using slices.

Last edited 2012


col(Posted 2012) [#4]
Oooooh Jesse!

"a"[0] ??

XD

If s[i]=Asc("a")


d-bug(Posted 2012) [#5]
Oooooh col!

"a"[0] is similar Asc("a") ;)

cheers

Last edited 2012


Yasha(Posted 2012) [#6]
Asc("a") optimises down to a literal 97 in the assembly output. "a"[0] doesn't, for whatever reason, and actually extracts the value each time (not that this is likely to make any noticeable difference).

Last edited 2012


ziggy(Posted 2012) [#7]
@Yasha: Funny to see that Monkey does the oposite.


Yasha(Posted 2012) [#8]
Which output are you checking? If you mean assembly post-C++, my guess would be that the C++ compiler catches the constant array access, 'cause they can do that easily, but -flto or equivalent isn't on and it's therefore not "aware" of Asc, which is presumably implemented as a library function for interoperability's sake (is it? I have no idea).

If you mean human-readable intermediate output in whatever language, the Monkey compiler probably doesn't bother with inlining at all (that is, it wouldn't if I was designing it), because it's rather pointless when all of the major target-compilers will take care of that step anyway.


Jesse(Posted 2012) [#9]
@col
I knew that.
I was just throwing a curve :-).


Alberto-Diablo(Posted 2012) [#10]

Const ASC_A:Byte = 97

For Local i:Int = 0 Until s.Length
    If s[i] = ASC_A Then Print "oregano"
Next



Enjoy ;)

Last edited 2012

Last edited 2012