我正在尝试通过更改每个字符来更改字符串.
现在我正在做的是一次读取字符串中的一个字符,尝试将其转换为ascii,并在值中添加一个字符.我有以下代码.
var phrase = textfield1.text
var i = 0
for character in phrase
{
var s = String(character).unicodeScalars
s[s.startIndex].value
println(s[s.startIndex].value)
if(i == 0)
{
s[s.startIndex].value += 1
}
if(i == 1)
{
s = s + 2
i = 0
}
}
Run Code Online (Sandbox Code Playgroud)
我的println打印出我输入的任何单词的正确值,但是我无法在if语句中操作它.当我尝试它时出现以下错误:
Could not find member 'value'
Run Code Online (Sandbox Code Playgroud)
甚至可以做我正在尝试的事情吗?
您收到该错误是因为a的value属性UnicodeScalar是只读的,但您尝试递增它.
请注意,更改循环中的内容不会产生任何影响phrase- 这是使用以下方法执行操作的方法map():
let advanced = String(map(phrase) {
(ch: Character) -> Character in
switch ch {
case " "..."}": // only work with printable low-ASCII
let scalars = String(ch).unicodeScalars // unicode scalar(s) of the character
let val = scalars[scalars.startIndex].value // value of the unicode scalar
return Character(UnicodeScalar(val + 1)) // return an incremented character
default:
return ch // non-printable or non-ASCII
}
})
Run Code Online (Sandbox Code Playgroud)
该unicodeScalars属性是只读的,因此您不能直接对其进行修改。
您可以做的是从(修改后的)Unicode标量构建一个新字符串:
var text = "HELLO !"
var newText = ""
for uni in text.unicodeScalars {
var val = uni.value
if val >= 0x41 && val < 0x5A { // If in the range "A"..."Y", just as an example
val += 1 // or whatever ...
}
newText.append(UnicodeScalar(val))
}
println(newText) // "IFMMP !"
Run Code Online (Sandbox Code Playgroud)
但是请注意,这val是Unicode值,而不是ASCII代码。val在修改之前,您可能需要添加检查是否在字母数字字符或类似字符的范围内。
Swift 3更新:(感谢@adrian。)
let text = "HELLO !"
var newText = ""
for uni in text.unicodeScalars {
var val = uni.value
if val >= 0x41 && val < 0x5A { // If in the range "A"..."Y", just as an example
val += 1 // or whatever ...
}
newText.append(Character(UnicodeScalar(val)!))
}
print(newText) // "IFMMP !"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6873 次 |
| 最近记录: |