gpt4 book ai didi

string - Clojure:在字符串中插入字符的惯用方法

转载 作者:行者123 更新时间:2023-12-04 10:53:08 24 4
gpt4 key购买 nike

我在 Clojure 中有一个字符串和一个我想放在第 n 个和第 (n+1) 个字符之间的字符。例如:假设字符串是“aple”,我想在“p”和“l”之间插入另一个“p”。

  (prn 
(some-function "aple" "p" 1 2))

;; prints "apple"
;; ie "aple" -> "ap" "p" "le" and the concatenated back together.

我发现这有点具有挑战性,所以我想我缺少一些有用函数的信息有人可以帮我写上面的“某个函数”,它需要一个字符串、另一个字符串、一个开始位置和一个结束位置并将第二个字符串插入开始位置和结束位置之间的第一个字符串?提前致谢!

最佳答案

比使用 seq 函数更有效:

(defn str-insert
"Insert c in string s at index i."
[s c i]
(str (subs s 0 i) c (subs s i)))

来自 REPL:
user=> (str-insert "aple" "p" 1)
"apple"

注意。这个函数实际上并不关心 c 的类型,或者在字符串的情况下它的长度; (str-insert "aple" \p 1)(str-insert "ale" "pp" 1)也可以工作(通常,将使用 (str c),如果 cnil 则为空字符串,否则 (.toString c))。

由于该问题要求以惯用​​的方式来执行手头的任务,我还会注意到我发现在专门处理字符串时使用面向字符串的函数更可取(在“语义适合”以及性能优势方面) ;这包括 subs和功能来自 clojure.string .见 the design notes at the top of the source of clojure.string 有关惯用字符串处理的讨论。

关于string - Clojure:在字符串中插入字符的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16578674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com