有没有办法在Swift的句子中随机大写字母?

时间:2017-01-13 06:10:07

标签: ios swift xcode string

只是想要一种方法来随机地将句子中的字母大写。有可能吗?

1 个答案:

答案 0 :(得分:0)

试试这个,

var string: String = "your string"
var chars: [Any] = []
var letterIndexes: [Any] = []
for i in 0..<string.characters.count {
    var ch: unichar = string[i]
    // add each char as a string to a chars collection
    chars.append("\(ch)")
    // record the index of letters
    if CharacterSet.letters.characterIsMember(ch) {
        letterIndexes.append((i))
    }
}

从letterIndexes中随机选择,以确定哪些字母为大写。将该索引处的chars数组的成员转换为大写。

var charsToUppercase: Int = 12
var i = 0
while i < charsToUppercase && letterIndexes.count {
    var randomLetterIndex: Int? = arc4random_uniform(((letterIndexes.count) as? u_int32_t))
    var indexToUpdate = CInt(letterIndexes[randomLetterIndex])
    letterIndexes.remove(at: randomLetterIndex)
    chars[indexToUpdate] = chars[indexToUpdate].uppercased()
    i += 1
}

剩下的就是将chars数组连接成一个字符串。

var result: String = (chars as NSArray).componentsJoined(byString: "")
print("\(result)")

参考this link for more information