通过移动给定整数来更新角色的最佳方法是什么
敏捷的性格很难操纵。 我有一个简单的要求: 对于给定的字符串,我想用“移动整数”对所有字母数字进行编码。
例如:“abc”,移动1:将变成“bcd”; “ABC”,移动 1 -> “BCD”。 需要注意的是,如果移动后范围大于“z”或“Z”,则应循环返回并重新从“a”或“A”开始计算。例如“XYZ”,移动 1 -> “YZA”
这在 Java 中很容易做到。但有人能告诉我什么是最干净的方法来快速做到这一点吗?
我做了类似的事情:
let arr: [Character] = Array(s)
for i in arr {
let curAsciiValue = i.asciiValue!
var updatedVal = (curAsciiValue + UInt8(withRotationFactor))
if i >= "A" && i <= "Z" {
newAsciiVal = 65
updatedVal = updatedVal - 65 >= 26 ? 65 + (updatedVal - 65) % 26 : updatedVal
} else if i >= "a" && i <= "z" {
newAsciiVal = 97
updatedVal = updatedVal - 97 >= 26 ? 97 + (updatedVal - 97) % 26 : updatedVal
}
}
最好的方法是什么?
Swift character is so hard to manipulate..
I have a simple request:
For a given string, I'd like to encode it with a "moving integer" for all the alphabetical digits.
For example: "abc", move 1: would become "bcd"; "ABC", move 1 -> "BCD".
One thing to note is, if after moving, the range it larger than "z" or "Z", it should loop back and calculate from "a" or "A" again. e.g "XYZ", move 1 -> "YZA"
This would be very easy to do in Java. But could anyone show me what would be the cleanest way to do it swift?
I've done something like:
let arr: [Character] = Array(s)
for i in arr {
let curAsciiValue = i.asciiValue!
var updatedVal = (curAsciiValue + UInt8(withRotationFactor))
if i >= "A" && i <= "Z" {
newAsciiVal = 65
updatedVal = updatedVal - 65 >= 26 ? 65 + (updatedVal - 65) % 26 : updatedVal
} else if i >= "a" && i <= "z" {
newAsciiVal = 97
updatedVal = updatedVal - 97 >= 26 ? 97 + (updatedVal - 97) % 26 : updatedVal
}
}
What should be best way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最好将所有逻辑放在一起扩展
Character
类型:扩展您可以使用
compactMap
映射字符串元素:并将字符序列转换回字符串:
或简单地放在一个衬里中:
Better to bring all your logic together extending the
Character
type:Expanding on that you can map your string elements using
compactMap
:And to convert the sequence of characters back to string:
or simply in one liner: