获取在Scala中替换子字符串的所有组合

时间:2018-03-27 07:20:46

标签: scala

假设我有字符串"foo bar foo barfoo foobar",我希望将"foo"替换为"baz"的所有可能组合。我如何在Scala中有效地完成这项工作?

预期输出为:

"baz bar foo barfoo foobar"
"foo bar baz barfoo foobar"
"baz bar baz barfoo foobar"
"foo bar foo barbaz foobar"
"baz bar foo barbaz foobar"
...

1 个答案:

答案 0 :(得分:4)

val str = "foo bar foo barfoo foobar"  //beginning string
val toReplace = "foo"

//get all the indices where "foo" is found
val xs = Stream.iterate(str.indexOf(toReplace))(x => str.indexOf(toReplace,x+1))
               .takeWhile(_>=0)

//get all combinations of indices and map each to a patched string
val result: Seq[String] = (1 to xs.length).flatMap(xs.combinations)
                       .map(_.foldLeft(str){_.patch(_, "baz", toReplace.length)})
//build each result string w/o separate intermediate strings
val result: Seq[String] = (1 to xs.length).flatMap(xs.combinations)
                   .map{combo =>
                     val sb = new StringBuilder(str)
                     combo.foreach(x => sb.replace(x, x+toReplace.length, "baz"))
                     sb.toString
                   }