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

Remove the first char to extract an integer (unhandled exception: Subscript)

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

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

我试过这样的事情:

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

但不幸的是,我收到了类似 unhandled exception: Subscript 的错误。 我认为这是因为有时我的字符串为空并且空字符串的大小不起作用。但我不知道如何让它工作......:/

在此先感谢您的帮助

此致。

我的错误很愚蠢,

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

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

希望对您有所帮助! :)

问题是在 x 不够长时调用 String.substring (x, 1, size 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" *)

但您可能需要考虑将您的函数命名为更通用的名称,以便它在更多意义上比执行 Kripke 变换(无论是什么)更有用。例如,您可能希望能够在第一次出现在字符串中的任何位置时提取一个实际的 int,而不管它前面有多少个非整数字符:

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