Sml 在第一个空格上拆分字符串

Sml 在第一个空格上拆分字符串,sml,smlnj,Sml,Smlnj,现在,我正在使用inputAll读取整个输入文件,然后使用String.tokens在每次出现空格时分割每个单词 val file = TextIO.openIn input val _input = TextIO.inputAll file val _ = TextIO.closeIn file String.tokens Char.isSpace _input 例如,“红蓝绿”看起来像这样 ["red", "blue", "green"] 但是,现在我想将其更改为仅在每行上第一次出现空格

现在,我正在使用inputAll读取整个输入文件,然后使用String.tokens在每次出现空格时分割每个单词

val file = TextIO.openIn input
val _input = TextIO.inputAll file
val _ = TextIO.closeIn file
String.tokens Char.isSpace _input
例如,“红蓝绿”看起来像这样

["red", "blue", "green"]
但是,现在我想将其更改为仅在每行上第一次出现空格字符时分割字符串

例如,“红蓝绿”应该是

["red", "blue green"]

我有一种感觉,我需要利用inputAll以外的东西来实现这一点,我的主要问题是如何使它只在每行的第一个空格处分裂。

TextIO。inputAll
很好。在这种情况下,
String.tokens
似乎不是适合该作业的工具。就我个人而言,我只需要编写自己的函数,使用
String.explode
String.implode
字符串
转换为
字符列表

fun splitCharsFirstSpace cs =
  case cs of
    [] => ([], [])
  | c :: cs' =>
      if Char.isSpace c then ([], cs')
      else let val (l, r) = splitCharsFirstSpace cs'
           in (c :: l, r)
           end

fun splitFirstSpace s =
  let
    val (l, r) = splitCharsFirstSpace (String.explode s)
  in
    (String.implode l, String.implode r)
  end
在上下文中,您可以如下使用它

val file = TextIO.openIn input
val contents = TextIO.inputAll file
val _ = TextIO.closeIn file
val lines = String.tokens (fn c => c = #"\n") contents
val lines' = List.map splitFirstSpace lines
例如,如果您的输入文件是:

red blue green
yellow orange purple pink
然后,
行“
将如下所示:

[("red", "blue green"), ("yellow", "orange purple pink")]

TextIO.inputAll
正常。在这种情况下,
String.tokens
似乎不是适合该作业的工具。就我个人而言,我只需要编写自己的函数,使用
String.explode
String.implode
字符串
转换为
字符列表

fun splitCharsFirstSpace cs =
  case cs of
    [] => ([], [])
  | c :: cs' =>
      if Char.isSpace c then ([], cs')
      else let val (l, r) = splitCharsFirstSpace cs'
           in (c :: l, r)
           end

fun splitFirstSpace s =
  let
    val (l, r) = splitCharsFirstSpace (String.explode s)
  in
    (String.implode l, String.implode r)
  end
在上下文中,您可以如下使用它

val file = TextIO.openIn input
val contents = TextIO.inputAll file
val _ = TextIO.closeIn file
val lines = String.tokens (fn c => c = #"\n") contents
val lines' = List.map splitFirstSpace lines
例如,如果您的输入文件是:

red blue green
yellow orange purple pink
然后,
行“
将如下所示:

[("red", "blue green"), ("yellow", "orange purple pink")]

这里是另一个使用函数drop、drop和splitl的选项 伴随着


这里是另一个使用函数drop、drop和splitl的选项 伴随着