Swift - 替换字符串的第 2 个字符



我有一个数组,其中包含一组三个字母的单词,这将是我正在开发的游戏的基础。我试图在我的 UILabel 中用下划线替换所有这些单词的第二个字符。用户必须点击正确的元音才能完成单词。

let games: [Game] = {
    let firstGame = Game(question: "1", answer: "BAT", choice_1: "A", choice_2: "O", choice_3: "U", choice_4: "E", image: "_bat", audio: "bat.wav")
    let secondGame = Game(question: "2", answer: "BIN", choice_1: "A", choice_2: "O", choice_3: "U", choice_4: "E", image: "_bin", audio: "bin.wav")
    let thirdGame = Game(question: "3", answer: "BOX", choice_1: "A", choice_2: "O", choice_3: "U", choice_4: "E", image: "_box", audio: "box.wav")
    return [firstGame, secondGame, thirdGame]
}()

我找到了replacingOccurrences功能,但这个功能只替换了一个字母或一组。用_字符替换我所有元音的最简单方法是什么。

var game: Game? {
    didSet {
        questionLabel.text = "Question (String(describing: game!.question)) of 10"
        if (game?.image) != nil {
            imageView.image = UIImage(named: (game?.image)!)
        }
        if let answerContent = game?.answer {
            answerField.text = answerContent.replacingOccurrences(of: "A", with: "_")
            answerField.addTextSpacing()
        }
    }
}

替换元音...

let vowels = CharacterSet(charactersIn: "AEIOU")
var string = "CAT"
if let range = string.rangeOfCharacter(from: vowels) {
    string.replaceSubrange(range, with: "_")
}
print(string) // C_T

替换第二个字符...

let start = string.index(after: string.startIndex)
// Only 1 character, so using a closed range with start == end
let range = start...start  
string.replaceSubrange(range, with: "_")
print(string)  // C_T

最新更新