假设有一个字符串“johngoestoschool”它应该变成“JoHnGoEsToScHoOl”并且如果它之间存在特殊字符则应该忽略它,例如给定字符串“jo $%@#hn ^ g oe!st#os& ch oo)l“答案应为”Jo $%@#Hn ^ G oE!sT#oS& cH oO)l“
从this回答,我们为了迭代我们可以做到:
let s = "alpha"
for i in s.characters.indices[s.startIndex..<s.endIndex]
{
print(s[i])
}
为什么我们不能在这里打印“i”的值? 当我们执行i.customPlaygroundQuickLook时,它键入int 0到int4。
所以我的想法是
if (i.customPlaygroundQuickLook == 3) {
s.characters.currentindex = capitalized
}
请帮助
答案 0 :(得分:2)
这应该解决你的功能,困难的部分只是检查天气是否是字母是字母,使用inout
并且替换范围会提供更好的性能:
func altCaptalized(string: String) -> String {
var stringAr = string.characters.map({ String($0) }) // Convert string to characters array and mapped it to become array of single letter strings
var numOfLetters = 0
// Convert string to array of unicode scalar character to compare in CharacterSet
for (i,uni) in string.unicodeScalars.enumerated() {
//Check if the scalar character is in letter character set
if CharacterSet.letters.contains(uni) {
if numOfLetters % 2 == 0 {
stringAr[i] = stringAr[i].uppercased() //Replace lowercased letter with uppercased
}
numOfLetters += 1
}
}
return stringAr.joined() //Combine all the single letter strings in the array into one string
}