只是想要一种方法来随机地将句子中的字母大写。有可能吗?
答案 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)")