JM Tech Power

jm-tech-power-official/JMLang

A programming language made by JM Tech Power

Public Uncategorized
Clone jm-tech-power-official/jmlang.jmproj
string.jml
# ===== string 库 =====
# 只用了 4 个原语:len、at、ord、chr

# 反转:"abc" → "cba"
func string.reverse s
    set r ""
    set i 0
    while $i < len $s
        set r $s at $i + $r
        set i $i + 1
    end
    ret $r
end

# 转大写:"Hello" → "HELLO"
func string.upper s
    set r ""
    set i 0
    while $i < len $s
        set c $s at $i
        set code ord $c
        if $code >= 97 and $code <= 122
            set code $code - 32
            set c chr $code
        end
        set r $r + $c
        set i $i + 1
    end
    ret $r
end

# 转小写
func string.lower s
    set r ""
    set i 0
    while $i < len $s
        set c $s at $i
        set code ord $c
        if $code >= 65 and $code <= 90
            set code $code + 32
            set c chr $code
        end
        set r $r + $c
        set i $i + 1
    end
    ret $r
end

# 截取:从 start 开始取 n 个字符
func string.sub s start n
    set r ""
    set i $start
    set stop $start + $n
    while $i < $stop and $i < len $s
        set r $r + $s at $i
        set i $i + 1
    end
    ret $r
end

# 查找:sub 第一次出现的位置,找不到返回 -1
func string.find s sub
    set n len $sub
    set i 0
    set last len $s
    set last $last - $n
    while $i <= $last
        call string.sub $s , $i , $n
        if $ret == $sub
            ret $i
        end
        set i $i + 1
    end
    ret -1
end

# 重复:"ab" 重复 3 次 → "ababab"
func string.repeat s n
    set r ""
    set i 0
    while $i < $n
        set r $r + $s
        set i $i + 1
    end
    ret $r
end