如何打印带索引号的字符?

时间:2015-11-26 11:30:11

标签: swift

我是一名初学程序员swift

我有一个字符串变量,需要带索引的打印字符 我的代码是:

let responcsestring = NSString(data: data, encoding: NSUTF8StringEncoding)

3 个答案:

答案 0 :(得分:0)

使用substringWithRange方法为给定范围生成子字符串。

例如,这将打印第一个字符:

let substring = someString.substringWithRange(NSRange(location: 0, length: 1))

print(substring)

答案 1 :(得分:0)

另一种方法是使用Swift stdlib String类型并访问它的字符数组。

let responsestring = String(data: data, encoding: NSUTF8StringEncoding) 
let secondCharacter = responsestring.characters[1]

这是一个有趣的 关于字符串及其在Swift中的不同表示的Blog post

答案 2 :(得分:-1)

小心!! func characterAtIndex(index:Int) - > unichar返回unichar(又名UInt16)

import Foundation
var s = "alpha".nulTerminatedUTF8.map{$0}
let data = NSData(bytes: &s, length: s.count)

let res = NSString(data: data, encoding: NSUTF8StringEncoding)
for i in 0..<res!.length {
    print(i, res!.characterAtIndex(i))
}

打印

0 97
1 108
2 112
3 104
4 97
5 0

...

var s = "♡仿♥".nulTerminatedUTF8.map{$0}
let data = NSData(bytes: &s, length: s.count)

let res = NSString(data: data, encoding: NSUTF8StringEncoding)
for i in 0..<res!.length {
    print(i, res!.characterAtIndex(i), UnicodeScalar(res!.characterAtIndex(i)))

}

打印

0 9825 ♡
1 20223 仿
2 9829 ♥
3 0 

并非每个unicode字符都可以表示为两个字节的长序列(UInt16)!你最好直接使用swift的String类型

var s = "".nulTerminatedUTF8.map{$0}
let data = NSData(bytes: &s, length: s.count)

let res = NSString(data: data, encoding: NSUTF8StringEncoding)
for i in 0..<res!.length {
    print(i, res!.characterAtIndex(i))

}

打印

0 55399
1 56893
2 0

即使原始字符串恰好是一个字符长。

let s = "".characters.count // 1

...您可以使用字符视图的索引到字符串

let s = ""
let idx = s.characters.startIndex
for i in 0..<s.characters.count {
    print(i, s[idx.advancedBy(i)])
}

打印

0