[Swift] Day02: a string in Swift, a string in swiftday02
Introduction
String
The string in is of the value type, and the value will be copied during transmission.NSString
Is referenced. We can usefor in
Traverse string:
var a : String = “a”for c in “Hello” { println(c)}
You can usecountElements
Calculate the number of characters in a string:
countElements(“1234567”) // 7
However, note that,countElements
And NSStringlength
Not always the same value, becauselength
The value of the UTF-16 type is used, not the Unicode character. For example, after the emoji expression is added, the result of the UTF-16 calculation is 2, and the Unicode calculation result is 1. See the following example:
var a = “Hello”countElements(a) // 6 - Unicodea.utf16Count // 7 - UTF16
You can use utf8 to get the UTF-8 representation. Similarly, you can use utf16 to get the representation of the UTF-16:
var b = “Hello”// 72 101 108 108 111 240 159 144 182for c in b.utf8 { println(c)}// 72 101 108 108 111 55357 56374for c in b.utf16 { println(c)}
To obtain the Unicode scalar, you can useunicodeScalars
To obtain:
// 68 111 103 33 128054”for scalar in b.unicodeScalars { print(“\(scalar.value) “)}
Substring
We cannot directly usestr[0...4]
To intercept the substring, because the StringSubscript
Must beString.Index
Of:
subscript(i: String.Index) -> Character { get }subscript(subRange: Range<String.Index>) -> String { get }
To obtain the SubString, You need:
let digits = “0123456789”let position = 3let index = advance(digits.startIndex, position)let character = digits[index] // -> “3”
Or usesubstringWithRange
Method:
var str = “abcdefg”str.substringWithRange(Range<String.Index>(start: advance(str.startIndex,2), end: str.endIndex))
Where,advance(i, n)
Equivalenti++n
, Only oneForwardIndexType
Can Returni
Nextn
. For exampleadvance(1, 2)
The returned result is1+2
That is, 3.
We can useExtension
To add the subscript of the integer type to the String:
var digits = “12345678901234567890”extension String{ subscript(integerIndex: Int) -> Character { let index = advance(startIndex, integerIndex) return self[index] } subscript(integerRange: Range<Int>) -> String { let start = advance(startIndex, integerRange.startIndex) let end = advance(startIndex, integerRange.endIndex) let range = start..<end return self[range] }}digits[5] // works nowdigits[4…6] // works now
AvailablerangeOfString()
To determine whether a substring is included:
var myString = “Swift is really easy!”if myString.rangeOfString(“easy”) != nil { println(“Exists!”)}
Splicing
It is common to splice values in an array into strings. We can use traversal to splice all elements:
let animals = [“cat”, “dog”, “turtle”, “swift”, “elephant”]var result: String = “”for animal in animals { if countElements(result) > 0 { result += “,” } result += animal}result // “cat,dog,turtle,swift,elephant”
Of course, there are also simpler methods,join
Function:
println(“a list of animals: ” + “,”.join(animals))
Availablemap
Add a list tag to each element:
println(“\n”.join(animals.map({ “- ” + $0})))
CapitalizedString can be used to uppercase the first letter of a string:
let capitalizedAnimals = animals.map({ $0.capitalizedString })println(“\n”.join(capitalizedAnimals.map({ “- ” + $0})))
You can usesorted()
Method to sort the elements in the group:
let sortedAnimals = animals.sorted({ (first, second) -> Bool in return first < second})println(“\n”.join(sortedAnimals.map({ “- ” + $0})))
You can use custom operators to implement strings.*n
The effect is like3*5=15
In this way:
func *(string: String, scalar: Int) -> String { let array = Array(count: scalar, repeatedValue: string) return “”.join(array)}println(“cat ” * 3 + “dog ” * 2)// cat cat cat dog dog
Decomposition
Based onFoundation
, We can usecomponentsSeparatedByString
Break down strings into Arrays:
import Foundationvar myString = “Berlin, Paris, New York, San Francisco”var myArray = myString.componentsSeparatedByString(“,”)//Returns an array with the following values: [“Berlin”, ” Paris”, ” New York”, ” San Francisco”]
If you want to break down multiple characters, you need to use another method:
import Foundationvar myString = “One-Two-Three-1 2 3”var array : [String] = myString.componentsSeparatedByCharactersInSet(NSCharacterSet (charactersInString: “- “))//Returns [“One”, “Two”, “Three”, “1”, “2”, “3”]
If you do not wantFoundation
For decomposition, you can use global functionssplit()
:
var str = “Today is so hot”let arr = split(str, { $0 == ” “}, maxSplit: Int.max, allowEmptySlices: false)println(arr) // [Today, is, so, hot]
Summary
In Swift,String
AndNSString
It is automatically converted. Although String is very powerful, it is not easy to use. You can refer to the ExSwift project on the Internet. The String. swift is a good complement to some frequently-used String content that Apple does not provide.
References
- Playing with Strings
- String reference guide for Swift
- Swift version of componentsSeparatedByString
- Strings in Swift