希望首先打印出重复的字符,然后打印出下一个字符数。
如从["a"、"a"one_answers"b"、"c"one_answers"c"]到["a"、"2"、"c"one_answers"2"]。
然而,我并没有解决这个问题。希望你对我的代码给出反馈,或者让我知道你的智慧如何解决这个问题。
import Foundation
var m : [String] = ["a","a","b","c","c"]
var count : Int = 0
var result : [String] = []
for i in 0..<m.count{
for word in m {
if m[i] == word{
count += 1
result.append(word)
}else{
count = 0
}
if count > 1{
result.append(String(count))
}
}
}
print("(count)")
print("(result)")
//["a", "a", "2", "a", "a", "2", "b", "c", "c", "2", "c", "c", "2"]
print(["a", "2","c","2"])// want to print it on the console like this.
它有一种类型,NSCountedSet
let m = ["a","a","b","c","c"]
let countedSet = NSCountedSet(array: m)
var result = [String]()
countedSet.forEach {
let count = countedSet.count(for: $0)
if count > 1 {
result.append(contentsOf: [$0 as! String, String(count)])
}
}
print(result)
您可以通过以下方法直接获得重复值
let fiteredValue = arrayList.filterDuplicates(includeElement: {$0 == $1})