使用一对一映射在Scala中连接两个字符串

时间:2019-01-16 04:28:13

标签: scala

我在Scala中有两个字符串

输入1 :“ a,c,e,g,i,k”

输入2 :“ b,d,f,h,j,l”

如何在Scala中连接两个字符串?

必需的输出 =“ ab,cd,ef,gh,ij,kl”

我尝试过类似的事情:

var columnNameSetOne:Array[String] = Array();    //v1 = "a,c,e,g,i,k"
var columnNameSetTwo:Array[String] = Array();    //v2 = "b,d,f,h,j,l"

如上所述获得输入数据后

columnNameSetOne = v1.split(",")
columnNameSetTwo = v2.split(",");

val newColumnSet = IntStream.range(0, Math.min(columnNameSetOne.length, columnNameSetTwo.length)).mapToObj(j => (columnNameSetOne(j) + columnNameSetTwo(j))).collect(Collectors.joining(","));

println(newColumnSet)

但是我在j上出现错误

此外,我不确定这是否行得通!

2 个答案:

答案 0 :(得分:3)

object Solution1 extends App {

  val input1 = "a,c,e,g,i,k"
  val input2 = "b,d,f,h,j,l"

  val i1= input1.split(",")
  val i2 = input2.split(",")

  val x =i1.zipAll(i2, "", "").map{
    case (a,b)=> a + b
  }

  println(x.mkString(","))

}
 //output : ab,cd,ef,gh,ij,kl

答案 1 :(得分:1)

易于使用列表上的zip功能。

val v1 = "a,c,e,g,i,k"
val v2 = "b,d,f,h,j,l"

val list1 = v1.split(",").toList
val list2 = v2.split(",").toList

list1.zip(list2).mkString(",") // res0: String = (a,b),( c,d),( e,f),( g,h),( i,j),( k,l)