2017-10-16 15 views
1

我有一個字符串「Hello」,我想用另一個字符串替換兩個索引之間的字符,比如說「Foo」。例如。我如何創建一個函數,用其他字符串替換給定的開始和結束索引的子字符串

(defn new-replace [orig-str start-index end-index new-string] ...) 

(= "Foollo" (new-replace "Hello" 0 2 "Foo")) => true 
(= "Foolo" (new-replace "Hello" 0 3 "Foo")) => true 

有什麼建議嗎?乾杯

+0

你嘗試過這麼遠嗎? – cfrick

+0

我已經使用subs創建了兩個字符串,不包括我想要刪除的字符串,並與中間的新字符串連接。看起來不那麼優雅,也許有更優雅的clojure慣用方式? @cfrick – Mehul

回答

0

這裏有一種方法:

(defn new-replace [orig-str start-index end-index new-string] 
    (str (apply str (take start-index orig-str)) 
     new-string 
     (apply str (drop end-index orig-str)))) 
0

Stringbuffer已經防阻一個替換功能:

(defn new-replace [orig-str start-index end-index new-string]                                      
    (str (.replace (StringBuffer. orig-str) start-index end-index new-string))) 
+0

如果您使用'StringBuilder'而不是'StringBuffer',這是一個很好的答案... – glts

相關問題