documentation for NSString.length
-
string.utf16.count
(string as NSString).length
let header = "NSString .utf16â encodedOffsetâ NSRangeâ .countâ .charactersâ distanceâ .unicodeScalarsâ .utf8â Description"
var format = " %3d %3d â %3d â %3d â %3d â %3d â %3d â %3d â %3d â %@"
format = format.replacingOccurrences(of: "â", with: "%@") // "â" acts as a placeholder for "%@" to align the text perfectly
print(header)
test("")
test("abc")
test("â")
test("ð¤ð»")
test("â¾test")
test("ð¨âð©âð§âð§")
test("ð¨\u{200d}ð©\u{200d}ð§\u{200d}ð¦")
test("ð¨ð©ð§ð¦")
test("\u{1F468}")
test("ð¶ð¼ð§ð½ð§ð¾ð¦ð»ð©ð¿ð§ð»ð¨ð½ð±ð½ââï¸ð±ð¼ââï¸ð§ð¾ðµð½ð§ð»ð´ð¾")
test("ä½ å¥½å")
test("Ù
رØبا", "Arabic word")
test("Ù
", "Arabic letter")
test("ש×××", "Hebrew word")
test("×", "Hebrew letter")
func test(_ s: String, _ description: String? = nil) {
func icon(for length: Int) -> String {
return length == (s as NSString).length ? "â
" : "â"
}
let description = description ?? "'" + s + "'"
let string = String(
format: format,
(s as NSString).length,
s.utf16.count, icon(for: s.utf16.count),
s.endIndex.encodedOffset, icon(for: s.endIndex.encodedOffset),
NSRange(s.startIndex..<s.endIndex, in: s).upperBound, icon(for: NSRange(s.startIndex..<s.endIndex, in: s).upperBound),
s.count, icon(for: s.count),
s.characters.count, icon(for: s.characters.count),
s.distance(from: s.startIndex, to: s.endIndex), icon(for: s.distance(from: s.startIndex, to: s.endIndex)),
s.unicodeScalars.count, icon(for: s.unicodeScalars.count),
s.utf8.count, icon(for: s.utf8.count),
description)
print(string)
}
NSString .utf16â encodedOffsetâ NSRangeâ .countâ .charactersâ distanceâ .unicodeScalarsâ .utf8â Description
0 0 â
0 â
0 â
0 â
0 â
0 â
0 â
0 â
''
3 3 â
3 â
3 â
3 â
3 â
3 â
3 â
3 â
'abc'
1 1 â
1 â
1 â
1 â
1 â
1 â
1 â
3 â 'â'
4 4 â
4 â
4 â
1 â 1 â 1 â 2 â 8 â 'ð¤ð»'
5 5 â
5 â
5 â
5 â
5 â
5 â
5 â
7 â 'â¾test'
11 11 â
11 â
11 â
1 â 1 â 1 â 7 â 25 â 'ð¨âð©âð§âð§'
11 11 â
11 â
11 â
1 â 1 â 1 â 7 â 25 â 'ð¨âð©âð§âð¦'
8 8 â
8 â
8 â
4 â 4 â 4 â 4 â 16 â 'ð¨ð©ð§ð¦'
2 2 â
2 â
2 â
1 â 1 â 1 â 1 â 4 â 'ð¨'
58 58 â
58 â
58 â
13 â 13 â 13 â 32 â 122 â 'ð¶ð¼ð§ð½ð§ð¾ð¦ð»ð©ð¿ð§ð»ð¨ð½ð±ð½ââï¸ð±ð¼ââï¸ð§ð¾ðµð½ð§ð»ð´ð¾'
3 3 â
3 â
3 â
3 â
3 â
3 â
3 â
9 â 'ä½ å¥½å'
5 5 â
5 â
5 â
5 â
5 â
5 â
5 â
10 â Arabic word
1 1 â
1 â
1 â
1 â
1 â
1 â
1 â
2 â Arabic letter
4 4 â
4 â
4 â
4 â
4 â
4 â
4 â
8 â Hebrew word
1 1 â
1 â
1 â
1 â
1 â
1 â
1 â
2 â Hebrew letter
-
(s as NSString).length
s.utf16.count
s.endIndex.encodedOffset
NSRange(s.startIndex..<s.endIndex, in: s)
-
s.count
s.characters.count
s.distance(from: s.startIndex, to: s.endIndex)
public extension String {
var nsrange: NSRange {
return NSRange(startIndex..<endIndex, in: self)
}
}
replace("ð¨âð©âð§âð§", characterAtIndex: "ð¨âð©âð§âð§".utf16.count - 1) // ð¨âð©âð§â�!