Search code examples
factor-lang

Single character from a string


To get the first character of a string I can:

(sc) "asd" first
97

An integer.

To make a string, the only way I could find was:

(sc) USE: strings math.ranges
(sc) "asd" first dup 
97
97    
(sc) [a,b] 
T{ range f 97 1 1 }    
(sc) >string
"a"

This seems sort of hacky / unwieldy. Are there a cleaner ways to get just one character from a string, as a string?


Solution

  • Factor distinguishes between characters, which are just unicode code points, which are just integers, and strings, which are just sequences of characters. Try for example:

    IN: scratchpad CHAR: A .
    65
    IN: scratchpad CHAR: Ö . 
    214
    IN: scratchpad CHAR: 字 .
    23383
    

    So you asking this question is probably a symptom of a misunderstanding of something. Regardless, to do your task:

    IN: scratchpad "Single character from a string" 5 swap nth 1string .
    "e"
    

    It grabs the sixth character and converts it into a one character long string.