1

假设ST是字符串,分别定义如下:

;; S
A
B
C

;; T
B
C
D

是否有类似的 clojure(script) 操作string-intersectionstring-union(因为没有更好的名称)满足以下条件?

(string-intersection S T)
;; => 
;; B
;; C

(string-union S T)
;; => 
;; A
;; B
;; C
;; D

如您所见,string-intersection将消除(逐行)不匹配的行(仅保留匹配的行),同时string-union具有合并行并忽略重复项的效果。

注意:我正在使用 clojurescript,但我想答案也可以推广到 clojure。

4

1 回答 1

2

根据您的描述,您似乎希望将字符串视为一组线并计算集合交集和并集。

要使用集合,您可以使用clojure.set命名空间。

首先将您的字符串转换为一组行:

(require '[clojure.string :as str]
         '[clojure.set :as set])

(def s "A\nB\nC")
(def t "B\nC\nD")

(def s-set (into #{} (str/split-lines s)))
(def t-set (into #{} (str/split-lines t)))

然后你可以计算你的并集和交集:

(def s-t-union (set/union s-set t-set))
;; => #{"C" "B" "A" "D"}

(def s-t-intersection (set/intersection s-set t-set))
;; => #{"C" "B"}

并对其进行排序:

(def s-t-union-sorted (sort s-t-union))
;; => ("A" "B" "C" "D")

(def s-t-intersection-sorted (sort s-t-intersection))
;; => ("B" "C")

您还可以将其转换回字符串:

(str/join "\n" s-t-union-sorted)
;; => "A\nB\nC\D"

(str/join "\n" s-t-intersection-sorted)
;; => "B\nC"
于 2016-04-25T07:16:53.617 回答