![]() |
|
string slicing using len() - Printable Version +- Boriel Basic Forum (https://forum.boriel.com) +-- Forum: Compilers and Computer Languages (https://forum.boriel.com/forumdisplay.php?fid=12) +--- Forum: ZX Basic Compiler (https://forum.boriel.com/forumdisplay.php?fid=11) +---- Forum: Help & Support (https://forum.boriel.com/forumdisplay.php?fid=16) +---- Thread: string slicing using len() (/showthread.php?tid=207) |
string slicing using len() - programandala.net - 2010-04-19 I didn't understand why a piece of my program didn't work as expected. I suspected something was wrong with the for-next loop. I tried some tests, simplified versions of the problem, and finally find out the following: Code: dim text as stringI tried the equivalent code in Sinclair Basic, and of course it worked as expected: Code: 10 LET A$="hello world!"Then I tried it without the loop: Code: dim text as stringThen I hardcoded some slicing values: Code: dim text as stringIs there something I'm missing in my code or is it a compiler issue? Re: string slicing using len() - boriel - 2010-04-19 It happens string slicing starts from 0 (not from 1). So it ranges from 0 to LEN(a$)-1. If you want your program work OK, you should do: Code: let a$="hello world"Notice also that FOR upper limit is evaluated ON EACH iteration (like C). So if len(a$) changes, the loop will shorten. So better use a temporary var l to store initial LEN(a$). Arrays subscripts starts from 0 to N-1 (like in C). But this behavior can be changed using --sinclair or --array-base switch. NOTE: I'm planning (for compatibility) an --string-base (so LEN and string-slicing will work exactly as in Sinclair BASIC, by specifying --string-base=1). Also with FOR, stating --constant-for etc... Re: string slicing using len() - programandala.net - 2010-04-19 boriel Wrote:Notice also that FOR upper limit is evaluated ON EACH iteration (like C). So if len(a$) changes, the loop will shorten. So better use a temporary var l to store initial LEN(a$). I learned it while debugging. It's an important difference with Sincllar Basic. boriel Wrote:Arrays subscripts starts from 0 to N-1 (like in C). But this behavior can be changed using --sinclair or --array-base switch. I forgot it! Thanks. One of my tests used "-2" intead of "-1" because of that. Anyway, the problem arises when trying to remove the last char of the string. Then "-2" cannot be used. I tried the following expression: Code: let text=text( to len(text)-2+(len(text)=1))It doesn't work because Code: (len(text)=1)doesn't return "1" when true, as I expected (Sinclair Basic does). I opened a new thread about this different issue. Re: string slicing using len() - boriel - 2010-05-03 A new compiler version (r1564) has been uploaded. It allows you to use --string-base parameter to tell the compiler which is the 1st base-index position in strings: Code: ./zxb.py --string-base=1 ...Also using --sinclair enables all this compatibilities with a single parameter. |