Algorithm 删除第一个字符以提取整数(未处理的异常:下标)

Algorithm 删除第一个字符以提取整数(未处理的异常:下标),algorithm,sml,Algorithm,Sml,我正在尝试编写一个只提取字符串中整数的函数 我所有的字符串都采用Ci格式,其中C是单个字符,i是整数。我希望能够从字符串中删除C 我试过这样的方法: fun transformKripke x = if size x > 1 then String.substring (x, 1, size x) else x 但不幸的是,我得到了一个类似未处理异常:Subscript的错误。 我认为这是因为有时候我的字符串是空的,空字符串的大小不起作用。但我不知道如何让它工作

我正在尝试编写一个只提取字符串中整数的函数

我所有的字符串都采用Ci格式,其中C是单个字符,i是整数。我希望能够从字符串中删除C

我试过这样的方法:

fun transformKripke x = 
    if size x > 1
    then String.substring (x, 1, size x)
    else x
但不幸的是,我得到了一个类似
未处理异常:Subscript
的错误。 我认为这是因为有时候我的字符串是空的,空字符串的大小不起作用。但我不知道如何让它工作…:/

提前谢谢你的帮助


向你问好。

我犯了个愚蠢的错误

字符串以
大小x-1结束,而不是
大小x结束。所以现在它是正确的:

fun transformKripke x = 
    if size x > 1
    then String.substring (x, 1, (size x)-1)
    else x

希望能有所帮助!:)

问题是当
x
不够长时调用
String.substring(x,1,大小x)

以下内容应该可以解决您当前的问题:

fun transformKripke s =
    if size s = 0
    then s
    else String.substring (s, 1, size s)
或者稍微漂亮一点:

fun transformKripke s =
    if size s = 0
    then s
    else String.extract (s, 1, NONE)  (* means "until the end" *)
但是你可能想考虑把你的函数命名为更一般的,这样它就可以比执行克里普克变换更有意义。例如,您可能希望能够在第一次出现在字符串中任何位置时提取实际整数,而不管前面有多少个非整数字符:

fun extractInt s =
    let val len = String.size s
        fun helper pos result =
            if pos = len
            then result
            else let val c = String.sub (s, pos)
                     val d = ord c - ord #"0"
                 in case (Char.isDigit c, result) of
                       (true, NONE)     => helper (pos+1) (SOME d)
                     | (true, SOME ds)  => helper (pos+1) (SOME (ds * 10 + d))
                     | (false, NONE)    => helper (pos+1) NONE
                     | (false, SOME ds) => SOME ds
                 end
    in helper 0 NONE
    end

在OCaml中,您可以使用模块
String
中的函数
sub