我有两个字符串需要合并。但是我必须像下面的格式那样合并。
var a = "abc"
var b = "def"
我需要这样做:adbecf
。
只是我尝试过的某种情况下的正常a + b。但无法解决。有什么想法吗?
更新:
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
}
答案 0 :(得分: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
简而言之
let c = zip(a,b).reduce("") { $0 + "\($1.0)\($1.1)" }
print(c)
将zip(::)与两个不等长的字符串一起使用将以忽略其余字符串结尾。
let a = "12345"
let b = "67"
let c = zip(a,b).reduce("") { $0 + "\($1.0)\($1.1)" }
print(c)//"1627"--> 345 is ignored
要解决此问题
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"
答案 1 :(得分:1)
此代码可以处理长度相等的字符串以及长度不相等的字符串的合并,无论是在a
循环内还是更长的情况下(如果b
较长时都可以结束
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)
}
忽略任何结尾字符
var out = ""
for (n, c) in a.enumerated() {
if n < b.count {
out.append(c)
out.append(b[b.index(b.startIndex, offsetBy: n)])
}
}