【问题标题】:Swift - Replace the 2nd character of a stringSwift - 替换字符串的第二个字符
【发布时间】:2017-04-05 08:33:08
【问题描述】:

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

【问题讨论】:

  • 循环查找所有元音?

标签: swift string replace


【解决方案1】:

替换元音...

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

【讨论】:

  • 但是如果字符串是CTA,它将是CT_
  • 感谢您添加第二段代码来为索引做同样的事情!
猜你喜欢
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-07
相关资源
最近更新 更多