This is the third day of my participation in Gwen Challenge

Swift’s String type is a value type. If you create a new string, the value is copied when it is constant, variable assignment, or passed in a function or method. In any case, a new copy of an existing string value is created and passed or assigned to that new copy


Initialization of a string

var emptyString = ""           // Initialize an empty string with a literal
let someString = "hello world" // Initialize a string with a literal

var anotherEmptyString = String(a)// Initialize method

//Character array initialization string
let charactersStr: [Character] = ["s"."w"."i"."f"."t"]
let str = String(charactersStr)
Copy the code

String nulling

Use the isEmpty attribute

if keyNote.isEmpty {
    print("Empty.")}Copy the code

Multiline string

A fixed sequence of text characters enclosed by a pair of three double quotes “””

let str = """If Beijing is surprisingly cold in winter, let me show you Hangzhou in winter."""
print(str)

logIf Beijing is exceptionally cold in winter, let me let you feel Hangzhou in winterCopy the code

Mutable string (var)

Mutable strings in Swift are different from mutable strings in OC, which chooses between two classes (NSString and NSMutableString). Swift uses let and var as the distinction

var message = "Product Manager"
message += "What?"  // What about product managers?
Copy the code

Compute the string length (count)

var string = "What about product managers?"
print(string.count)    / / 7
Copy the code

String traversal

  • throughfor-inLoop through the String to access each part of the StringCharactervalue
for character in "swift" {
    print(character)
}

log:
s
w
i
f
t
Copy the code
  • useindicesProperty creates a Range of all indexes used to access individual characters in a string.
let someString = "dog"
for index in someString.indices {
    print(someString[index])
}
// d
// o
// g
Copy the code

String splicing

let message = "Product Manager"
let result = "\(message) what about?"  // What about product managers?
Copy the code
  • String values can be associated with addition operators+Add (or concatenate) together to create new String values
let str1 = "Product Manager"
let str2 = "What?"
var message = str1 + str2 // What about product managers?

var message = "Product Manager"
message += "What?"  // What about product managers?
Copy the code
  • Use a String methodappend()Append the Character value to the String variable
let mark: Character = "?"
var string = "What about product managers?"
string.append(mark)  // What about product managers?
Copy the code

Index of string

  • startIndexIs the index to get the first character in a character creation
  • endIndexIs the index of the character after the last character in the string.
  • index(before:)Get the previous index
  • index(after:)Get the next index
  • index(_:offsetBy:)Gets the index of the corresponding offset
let someString = "developer"
print(someString[someString.startIndex])    //d
print(someString[someString.index(before: someString.endIndex)])    //r
print(someString[someString.index(after: someString.startIndex)])   //e
let index = someString.index(someString.startIndex, offsetBy: 5)
print(someString[index])    //o
Copy the code

String insertion

  • insert(_:at:)Can beA single characterInserts into a string at the specified index
var someString = "developer"
someString.insert("!".at: someString.endIndex)
// someString = developer!
Copy the code
  • insert(contentsOf:at:)Specifies the contents of another string to be inserted at the index
var someString = "developer"
someString.insert(contentsOf: "are great".at: someString.endIndex)
// someString = developer are great
Copy the code

Deletion of strings

Remove (at:) removes a single character from the string at the specified index

var someString = "developer!"
someString.remove(at:someString.index(before: someString.endIndex))
// someString = developer
Copy the code

RemoveSubrange (_:) removes a substring from the specified index of a string

let range = someString.index(someString.endIndex, offsetBy: -10) ..< someString.endIndex
someString.removeSubrange(range)
// someString = developer
Copy the code

String substitution

let str = "aa$$bb$$cc$$dd"
let str2 = str.replacingOccurrences(of: "$$".with: "* *")  
//aa**bb**cc**dd
Copy the code

String interception

Most of the SubString functions in Swift are just like strings, which means you can manipulate both substrings and strings in the same way. The difference between String and SubString, however, is that the SubString can reuse the memory of the original String, or the memory of another SubString. (String has the same optimization, but if two strings share memory, They will be equal. This optimization means that you don’t need to use performance to copy memory until you modify strings and substrings. Because it reuses the memory space of the original String, the memory space of the original String must remain until its SubString is no longer used and you only use SubString if you need to manipulate strings for a short period of time. When you need to save the result for a long time, convert the SubString to an instance of String

let str = "developer"
let index = str.firstIndex(of: "v")?? str.endIndexlet sub = str[...index]    //dev
let sub1 = str[index ..< str.endIndex]    //veloper
let sub2 = str[str.startIndex ..< index]  //de

// Convert the result to a String for long-term storage
let newString = String(sub)
Copy the code

STR is a String, which means it has a space in memory to hold the character set. And since sub is a SubString of STR, it reuses the memory space of STR. Instead, newString is a String — it is created using SubString and has its own piece of memory


Compare strings (string character equality, prefix equality, and suffix equality)

  • Used to determine whether strings/characters are equal= =and! =
let str1 = "develop are great"
let str2 = "develop are great"
if str1 == str2 {
   print("Same string")}Copy the code
  • The prefix/suffix is equal

Check if a String has a specific prefix/suffix by calling the hasPrefix(_:) and hasSuffix(_:) methods of the String, both of which take a String argument and return a Boolean value

let romeoAndJuliet = [
    "Act 1 Scene 1: Verona, A public place"."Act 1 Scene 2: Capulet's mansion"."Act 1 Scene 3: A room in Capulet's mansion"."Act 2 Scene 1: Outside Capulet's mansion"."Act 2 Scene 2: Capulet's orchard"."Act 2 Scene 3: Outside Friar Lawrence's cell"
]
var act1SceneCount = 0
for scene in romeoAndJuliet {
    if scene.hasPrefix("Act 1 ") {
        act1SceneCount += 1
    }
}
print("There are \(act1SceneCount) scenes in Act 1")
//There are 3 scenes in Act 1

var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
    if scene.hasSuffix("Capulet's mansion") {
        mansionCount += 1
    } else if scene.hasSuffix("Friar Lawrence's cell") {
        cellCount += 1
    }
}
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
//3 mansion scenes; 1 cell scenes
Copy the code

Special characters in literals

  • Empty \ 0 (characters), \ (backslash), \ t tabs (level), (newline), \ r \ n (carriage return), “(double quotes), the ‘(single quotation marks)
  • Unicode scalar, written as\u{n}(u is lowercase), where n is any one to eight hexadecimal number and availableUnicodeDigit code.
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
let dollarSign = "\u{24}"        
let blackHeart = "\u{2665}"      
let sparklingHeart = "\u{1F496}" 

print(wiseWords)  // "Imagination is more important than knowledge" - Einstein
print(dollarSign)  // $, Unicode scalar U+0024
print(blackHeart)  // ♥, Unicode Scalar U+2665
print(sparklingHeart)  // 💖, Unicode scalar U+1F496
Copy the code