Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

How to call a specific character in, and length of a string? [SC1]

Is there any way of getting the length of a string, and then display a specific character in that string?

Basically I'm trying to recreate something I did on my first computer, a ZX Spectrum. In ZX Basic (the only thing I can really compare it to) I'd type something like...
1 LET text$ = "Cheesestrings"
2 PRINT LEN text$
(for those wondering, the $ at the end of text$ indicated that the variable was a string and not a number or other value)

The resulting output would be 13.

If I wanted to show a specific character I could do
3 PRINT text$(5)

The resulting output would s.

Is there any way to do this in SugarCube, that preferably doesn't involve Javascript as I'm having problems getting my head around JS.

Thanks in advance

Comments

  • edited September 2015
    /* Set the story variable $text to "Cheesestrings". */
    <<set $text to "Cheesestrings">>
    
    /* Print the length of $text. */
    <<print $text.length>>
    
    /* Print the 5th character (indices are 0-based). */
    <<print $text[4]>>
    
  • edited September 2015
    edit: it looks like TheMadExile answer this at the same time I did. lol

    As far as I know SugarCube does not have any built-in macros for determining the length of a string (text) value, nor does it have it's own substring function.
    But the Javascript for both are very simple.

    1. String length example:
    <<set $text to "Cheesestrings">>
    length is: $text.length
    

    2. There are two basic methods for access a specific character in a string based on its index position:

    note: Javascript string are zero-based indexed, which means the first character is at index zero not index one, the second character is at index one not two, and so on.

    2a. Array referencing
    A string value can be treated like an array of individual characters. The following example access the fifth character in the string: (which is index four)
    <<set $text to "Cheesestrings">>
    the fifth character is: $text[4]
    
    2b. String charAt
    The following example access the fifth character in the string: (which is index four)
    <<set $text to "Cheesestrings">>
    the fifth character is: <<print $text.charAt(4)>>
    
  • Oh thanks guys :)

    I tried text position one by myself that TheMadExile gave, but I was using normal brackets as opposed to square brackets (doh!).

    Once again, many thanks :)
Sign In or Register to comment.