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

时间:2017-04-05 08:33:08

标签: swift string replace

我有一个包含三个字母单词的数组,它将成为我正在进行的游戏的基础。我试图用 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()
        }
    }
}

1 个答案:

答案 0 :(得分:2)

替换元音......

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