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

标签 string clojure concatenation

我在 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/

相关文章:

c# - Int 到带前导 0 的字符串转换

c# - 固定长度的字符串作为值类型用于 MemoryMappedViewAccessor

javascript - 结合 JSON 文件与 grunt-contrib-concat

C# append 字典

python - 连接没有顶行的大文件 - python 或 bash?

javascript - 在javascript中从数组中删除空字符串

python - 将for循环的输出写入python中的csv

oop - 在 Clojure 中扩展类的问题 : ClassFormatError: Duplicate field name&signature

clojure - 如何在 clojurescript 中获取名称中带有破折号的属性?

clojure - Clojure 1.5.1 中缺少 defnk