Shop OBEX P1 Docs P2 Docs Learn Events
Iterating Over String — Parallax Forums

Iterating Over String

John BoardJohn Board Posts: 371
edited 2013-03-22 19:24 in Propeller 1
How does one interate over a string...

For example, in python you might do:
s = "String"
for x in s:
    print x

How might I do this in SPIN?

Thanks,

John

Comments

  • JonnyMacJonnyMac Posts: 9,108
    edited 2013-03-21 22:53
    If you're printing then you can use that .str() method which is probably part of your output object.

    There's no string type in Spin, but you can define a string as an array of bytes in a DAT block.
    dat
    
    MyStr           byte    "string", 0
    
    
    pub main | p, c
    
      p := @MyStr
      repeat
        c := byte[p++]
        if (c > 0)
          print(c)
        else
          quit
    
  • Bobb FwedBobb Fwed Posts: 1,119
    edited 2013-03-22 09:11
    Or you could replace @MyStr with string("string") and skip the DAT section.
    But as he said there is no string type, it's just an array of bytes, the string() function just creates this array in-line, but it functions the same as declaring a string in DAT, except it automatically terminates the string with a 0-byte and returns the address of the string.

    An alternative:
    p := string("string")
      REPEAT strsize(strAddr)                             ' for each character in string
        print(byte[p++])                                  '   write the character
    

    But then you'll have to reset p every time you do that. It would be better in a method like this:
    PUB Main
      print_str(string("string"))
    
    PRI print_str (strAddr)
    
      REPEAT strsize(strAddr)                             ' for each character in string
        print(byte[strAddr++])                            '   write the character
    
  • John BoardJohn Board Posts: 371
    edited 2013-03-22 19:24
    Cheers, much appreciated - I'm modifying FemtoBasic for a small project of mine. I'm going off to be a leader on a primary school kid's camp, and the theam is "retro robots", and they were needing some decor for the dining room, so I suggested making some kind of "retro computer system" - I was planning on doing this with FemtoBasic, with a few things added.

    Basically this is for slowly printing a string, so printing a string to the TV one character at a time, to get that kind of "Typewriter" feel...

    Anyway, thanks for the help!

    -John
Sign In or Register to comment.