To get the first 50 characters of a String
, I can do
s.substringToIndex(s.startIndex.advancedBy(50)))
How can I get the first 50 unicode scalars of a String
?
I can get a String.UnicodeScalarView
object using s.unicodeScalars
but I don't know how to go from there.
s.unicodeScalars
returns a String.UnicodeScalarView
which conforms to CollectionType
. You can get a subsequence of the collection with
u = s.unicodeScalars
u[u.startIndex ..< u.startIndex.advancedBy(50)]
or, in the case of an initial sequence, more simply with
u.prefix(50)
There is a small difference: Subscripting requires that the specified subrange exists, and will terminate with a runtime exception otherwise. prefix()
truncates at the given index, ie it returns a subsequence with 50 or less elements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.