因此,该函数应该采用 3 个都是字符串的参数。第一个是原始字符串。第二个是应该更改字符串中的字母。第三个是字母应该改成什么。例如,
~ (switch-up "aabcc" "abc" "def")
“ddeff”
我什至不知道如何从这个开始。有什么帮助吗?
因此,该函数应该采用 3 个都是字符串的参数。第一个是原始字符串。第二个是应该更改字符串中的字母。第三个是字母应该改成什么。例如,
~ (switch-up "aabcc" "abc" "def")
“ddeff”
我什至不知道如何从这个开始。有什么帮助吗?
这看起来像家庭作业,所以我将给您一些提示,以使用您可用的程序解决问题。首先将问题拆分为更简单的部分 - 首先,实际switch-up
过程基本上迭代输入字符串中的每个字符,依次处理每个字符并使用结果构建一个新字符串。提示:使用string-ref
andsubstring
检索字符串中的第一个字符和其余字符 - 将其视为字符串的car
and cdr
。
(define (switch-up lst letters replacements)
(if <???> ; if the string is empty
<???> ; return the empty string ""
(string-append (replace <???> <???> <???>) ; otherwise string-append the replacement of the first character in the string
(switch-up <???> letters replacements)))) ; and advance the recursion over the rest of the string
其次,我们需要一个replace
过程,给定单个字符以及字母和替换,如果没有找到,则返回替换的字符串或具有相同输入字符的字符串:
(define (replace c ls rs)
(let ((idx (index-of ls c))) ; get the index of c in the `ls` string
(if idx ; if the index was found
(string (string-ref rs idx)) ; then get the corresponding value from `rs`
(string c)))) ; otherwise, return c unchanged
最后,我发现对前面的过程定义一个帮助程序很有用,它返回字符串中字符的索引ls
(或者#f
如果在字符串中没有找到该字符),所以很容易在替换字符串中找到它. str
提示:转换成字符列表将非常有用,使用string->list
(define (index-of str c)
<???>) ; ToDo: return the 0-based index of c inside str
不要忘记测试所有内容:
(switch-up "aabcc" "abc" "def")
=> "ddeff"
备选方案:string->list
如果您首先将字符串转换为字符列表(使用),然后在最后将它们转换回字符串,使用 ,则该问题可能更容易解决list->string
。
概述:创建从旧字母到新字母的映射。遍历原始列表,将每个旧字母替换为新字母。假设所有参数都是列表(否则需要string->list
):
(define (switch-up list old new)
(let ((old-to-new (map cons old new)))
(let switching ((list list) (result '())
(if (null? list)
(reverse result)
(switching (cdr list)
(cons (cond ((assoc (car list) old-to-new) => cdr)
(else (car list)))
result))))))