0

I have two strings which I need to merge. But I have to merge like below format.

var a = "abc"
var b = "def"

I need to do like : adbecf.

Just an normal a+b with some condition I tried. But not able to solve. Any idea ?

update :

let stringA = "abc"
 let stringB = "def"


func mergeStrings(a: String, b: String) -> String {

    let val = zip(a,b).reduce("") { (result, arg1) in
    let (char1, char2) = arg1
    return result + "\(char1)\(char2)"
}
return val
}
Sai Kumar
  • 67
  • 1
  • 1
  • 7

2 Answers2

2
let a = "abc"
let b = "def"
let c = zip(a,b).reduce("") { (result, arg1) in
    let (char1, char2) = arg1
    return result + "\(char1)\(char2)"
}
print(c)//adbecf

in short

let c = zip(a,b).reduce("") { $0 + "\($1.0)\($1.1)" }
print(c)

Using zip(::) with two unequal length strings will end with ignoring remaining strings.

let a = "12345"
let b = "67"
let c = zip(a,b).reduce("") { $0 + "\($1.0)\($1.1)" }
print(c)//"1627"--> 345 is ignored

To fix this use

if a.count > b.count {
    c = c + String(a[b.endIndex...])
} else if b.count > a.count {
    c = c + String(b[a.endIndex...])
}
print(c)//"1627345"
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
1

This code handles merging of equally length string and also unequally length strings either inside the loop of a is longer or at the end if b is longer

var out = ""
for (n, c) in a.enumerated() {
    out.append(c)
    if n < b.count {
        out.append(b[b.index(b.startIndex, offsetBy: n)])
    }
}
if b.count > a.count {
    out += b.suffix(a.count)
}

To ignore any trailing characters

var out = ""
for (n, c) in a.enumerated() {
    if n < b.count {
        out.append(c)
        out.append(b[b.index(b.startIndex, offsetBy: n)])
    }
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52