返回swift中的重复字符

时间:2017-11-08 05:39:53

标签: swift return return-value

我试图在swift中找到第一个重复的字符,并返回找到的字符。我在这段代码中遇到了一堆错误,我不知道为什么这不起作用。

var myArry = "Hello, World"
var counts = [Character]()

func findRepeating(myArry: String) -> Character
{
    counts = []
    for char in myArry.characters
    {
        if char in counts
        {
            print("Character found")
            return char
        }
        else
        {
            counts.append(char)
        }
    }
    return "A"
}

2 个答案:

答案 0 :(得分:0)

无需使用字典。您可以使用一组字符并在循环内插入集合中的每个字符。如果插入成功与否,set insert方法返回bool插入的信号。如果不成功,请在该循环上提前退出该字符:

extension String {
    var firstRepeating: Character? {
        var set: Set<Character> = []
        for char in self {
            if !set.insert(char).inserted {
                return char
            }
        }
        return nil
    }
}
let myString = "Hello, World" 

if let firstRepeating = myString.firstRepeating {
    print(firstRepeating)   // "l\n"
}

答案 1 :(得分:0)

最简单的答案:

let str = "abcdefghijkhlmnop"
var count = 0
for char in str.characters {
    for charNext in str.characters {
        if (char == charNext) {
            count += 1
            if (count > 1) {
                return char           // h
            } 
        }
    }
    count = 0
}