Introduction to Strings
- Strings are used very frequently in any development.
- Differences between the strings in OC and Swift
- When the string type is nsstring in OC, the string type in Swift
- The string @ "" In OC, the string "" in Swift
String
Reasons for use
String
is a structural body with higher performance
NSString
is an OC
object with slightly poor performance
String
Supports direct traversal
Swift
Provides String
NSString
seamless transitions between and
Use of String Traversal string
// 字符串遍历var str = "Hello, Swift"for c in str.characters { print(c)}
string concatenation
- Concatenation of two strings
let str1 = "Hello"let str2 = "World"let str3 = str1 + str2
- Concatenation of strings and other data types
let name = "why"let age = 18let info = "my name is \(name), age is \(age)"
let min = 3let second = 4let time = String(format: "%02d:%02d", arguments: [min, second])
Interception of strings
- Special interception methods are available in Swift
- The way is very troublesome
- Index creation is more troublesome
- The simple way is to convert a string into NSString to use the
- After the identifier, add: as NSString
Import UIKit//1. Define the string: Swift defines the string without @, directly a C-language string ""Let str ="Hello World"//2. Traversing characters in a string: A space is also considered a character forCinchstr.characters {print (c)}//3. Concatenation of strings//3.1. Stitching between StringsLet str1 ="Small size brother"Let str2="IT Education"Let result= str1 +str2//3.2. Stitching between strings and other identifiersLet age = -Let name=" Why"Let height=1.88//format for stitching other identifiers: \ (name of identifier)Let info ="my name is \ (name), age is \ (age), height is \ (height)"//3.3. String formatting:%02d represents the placeholder meaning, two bits, less than two bits of 0 to complement, arguments parameter type is an array, [Min, second] represents an array, swift array can hold the basic type of data, with [] to represent//Music Player:Let min =3Let second=GenevaLet timestr= String (format:"%02d:%02d", arguments: [min, second])//4. String interception: From and to are includedLet urlstring ="www.520it.com"//turn String type to NSString type string as NSStringLet Header = (urlstring asnsstring). substring (to:3) Let Middle= (urlstring asnsstring). Substring (With:nsrange (location:4, Length:5)) Let footer= (urlstring asnsstring). substring (from:Ten)
Swift Learning Day Fifth: string