2017-10-16 16 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

相关问题