gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:22:36 26 4
gpt4 key购买 nike

我有一个数组,其中包含一组三个字母的单词,这将是我正在开发的游戏的基础。我试图在我的 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

关于Swift - 替换字符串的第二个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43225948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com