如何在SML中按指定格式打印无换行符的二维字符数组?
实现SML二维字符数组的逐行打印
当然没问题!要实现这个需求,我们只需要把二维字符数组的每一行转换成字符串,再逐行打印(手动加上换行符就行)。下面给你两种可行的实现方式:
方法一:递归遍历行索引
这种方式用递归处理每一行,逻辑清晰易懂:
首先定义你的二维数组:
val arr = Array2.fromList [[#"a", #"b", #"c"], [#"d", #"e", #"f"], [#"g", #"h", #"i"]];
然后实现打印函数:
fun print2DCharArray arr = let val totalRows = Array2.nRows arr // 获取数组的总行数 fun printRow currentRow = if currentRow >= totalRows then () // 遍历完所有行就停止 else let // 取出当前行的vector,转成char列表再拼接成字符串 val rowStr = String.implode (Vector.toList (Array2.row arr currentRow)) in print (rowStr ^ "\n"); // 打印字符串+换行符 printRow (currentRow + 1) // 递归处理下一行 end in printRow 0 // 从第0行开始打印 end;
调用函数就能得到你想要的输出:
print2DCharArray arr;
输出结果:
abc def ghi
方法二:用列表迭代简化代码
如果你更喜欢简洁的写法,可以利用SML的列表工具函数来实现:
fun print2DCharArray arr = let val totalRows = Array2.nRows arr // 定义处理单行的函数:取出行→转字符串→打印(加换行) fun processRow rowIdx = print (String.implode (Vector.toList (Array2.row arr rowIdx)) ^ "\n") in // 生成0到totalRows-1的索引列表,逐个应用processRow函数 List.app processRow (List.tabulate (totalRows, fn i => i)) end;
核心逻辑说明
两种方法的核心思路是一致的:
- 用
Array2.row获取指定行的字符vector - 用
Vector.toList把vector转成char列表,再通过String.implode拼接成完整字符串 - 手动添加
"\n"换行符,确保每行单独显示
内容的提问来源于stack exchange,提问作者StrikeLeader
相关产品推荐
相关产品推荐

