Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 使用索引进行多个字符串替换_String_Clojure_Reduce - Fatal编程技术网

String 使用索引进行多个字符串替换

String 使用索引进行多个字符串替换,string,clojure,reduce,String,Clojure,Reduce,我使用以下食谱替换文本中的非唯一子字符串: (defn string-splice "cookbook recipe: http://gettingclojure.wikidot.com/cookbook:strings Given three arguments, string-splice will replace a portion of the old string at the given offset equal to the length

我使用以下食谱替换文本中的非唯一子字符串:

 (defn string-splice
    "cookbook recipe: http://gettingclojure.wikidot.com/cookbook:strings
     Given three arguments, string-splice will replace a portion of the old string at the       
     given offset equal to the length  of the replacement. The resulting string will be the      
     same  length as the original. The optional fourth argument 
     specifies the length of text to be replaced. If this argument length is greater than the    
     length of the new string, then the result will be shorter than the original string."

     ([target new offset] (string-splice target new offset (count new)))
     ([target new offset length]
     (str  (subs target 0 offset)   new (subs target (+ offset length))  )   ) )
现在假设我有以下拼写错误的字符串

 (def bad-st "mary had a littl lam whose fleec was whiteas snw.")
以及以下更正列表,其中包含相关索引,指示拼写错误的单词在bad st中出现的位置:

 (def corrections '(Mary 0 Little 11 fleck 27 white as 37 Snow 45))
如果我想累积地将这些更正替换到字符串中,同时移动字符串中的字符以适应比拼写错误的子字符串更长或更短的更正,我可以使用为字符串提供的reduce代码版本

但是,这无法正确移动原始文本中的字符。输出是

 "Mary had a Littlelam whose fleck was white asSnow"

有谁能告诉我我做错了什么并提出解决方案吗?

使用字符串拼接的基本问题是传递了错误的第四个参数,该参数必须是替换子字符串的长度-传递的是替换子字符串的长度。所以你需要在正确的位置找到坏单词的长度

(defn wsize-at 
  "size of word (non-white sequence) at position n in string s"
  [n s]
  (let [[head tail] (split-at n s)]
    (count (take-while #(not (Character/isWhitespace %)) tail))))
使用reduce时出现的问题是,如果替换字符串和替换字符串的长度不同,则会在字符串的后面抛出索引。您可以通过从字符串末尾向后操作来解决此问题:

(reduce (fn [st [s n]] (string-splice st s n (wsize-at n st)))
  bad-st 
  (reverse (partition 2 corrections)))

我不确定字符串拼接是否是此任务的正确工具。校正偏移位于原始字符串中;另一种方法是使用这些偏移量提取原始字符串的未更改段,比如使用函数good parts,good parts bad st[0 11 27 37 45]给出[had a,lam what,was,snw.]-wsize at将是实现的一部分。然后将其与[Mary、Little、fleck、white as、Snow]交错,并对结果应用str以得到所需字符串。

很好的修复。在你扩展你的帖子之前,我昨晚确实尝试过你的交错建议,但这更好。
(reduce (fn [st [s n]] (string-splice st s n (wsize-at n st)))
  bad-st 
  (reverse (partition 2 corrections)))