Swift Strings and Characters

multiline string literals

  • if you need a string that spans several lines, use a multiline string literal that is a sequence of characters surrounded by 3 double quotation marks
let quotation = """
to be 
or not to be
that's a question
"""
  • multiline string literals start or end with no line break, it begins on the first line after the opening quotations and ends with the last line befroe the closing quotations
let str1 = "they are same"
let str2 = """
they are same
"""
  • if you don’t want line breaks to be parts of string values, write a backslash at the end of those lines
let a = """
to be, \
or not to be,\
that's a question
"""
//to be, or not to be, that's a question
  • the whitespace before the closing quotations tells swift what whitespace to ignore before all of other lines
let str = """
    to be,
        or not to be,
    that's a question
    """
//to,
//  or not to be,
//that's a question

initializing a empty string

  • assign an empty string literal to a variable
  • initialize a new String instance with no parameter
var emptyString = ""
var anotherEmptyString = String()
  • you can find out whether a string value is empty by checking its isEmpty
if emptyString.isEmpty {
    print("nothing to see here")
}

string mutability

var variableString = "horse"
variableString += " and carriage";

strings are value types

when you pass a string value to a function or assign it to a constant or variable, a new copy of this existing string value is created, and the new copy is passed or assigned, not the original version

string indices

  • a string value has a associated index type, string.Index
  • use the startIndex property of string to access the position of the first character of the string
  • the endIndex property is the last position of the last character of the string and the endIndex is not a valid argument to a string’s subscript
  • when a string is empty, startIndex equals to endIndex
  • you can access the indices before or after the given index, using the index(before:) and index(after:) methods
  • you can access the index farther away from the given index by using the index(_:offsetBy:)
let greeting = "Guten tag!"
greeting[greeting.startIndex] //G
greeting[greeting.index(before: greeting.endIndex)]//!
greeting[greeting.index(after: greeting.startIndex)]//u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]//a
  • use the indices property to access all indices of characters in a string
for index in greeting.indices {
    print(greeting[index])
}

you can use the index methods on any type conforming Collection protocol, such as Array, Set, Dictionary

inserting and removing

  • use the insert(:_at:) method to insert a single character into a string at a specific index
  • use the insert(contentsOf:at:) method to insert the contents of another string at a specific index
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
//hello!
welcome.insert(contensOf: " there", at: welcome.index(before: welcome.endIndex))
//hello there!
  • use the remove(at:) method to remove a character at a specific index
  • use the removeSubstring(_😃 method to remove a substring at a specific range
welcome.remove(at: welcome.index(before: welcome.endIndex))
//hello there
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubstring(range)
//"hello"

you can use insert(:at:) insert(contentsOf:at:) remove(at:) removeSubstring(😃 methods on any type conforming to the RangeReplaceableCollection protocol, such as Array, Set, Dictionary

Substring

  • use a subscript to get a substring that is of type Substring, not String
  • most of methods of Substring are the same as String
  • you use Substring for only a short amount of time while performing actions on a string. when you are ready to store the result for a longer time, convert the Substring to an instance of String
let greeting = "hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
//beginning = "hello"
let newString = String(beginning)
  • a Substring can reuse the part of the memory that is used to stored the original string, or part of the memory that is stored other substring.

String And Character equality

  • string and character equality is checked with “==” and “!=” operators
let quotation = "asdfzxcv"
let sameQuotation = "asdfzxcv"
if quotation == sameQuotation {
    print("they are the same strings")
}

Prefix And Suffix Equality

  • use hasPrefix(_😃 and hasSuffix(_😃 methods to check whether a string has a particular prefix or suffix. both of 2 methods return bool 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 1 Scene 4: A street outside Capulet's mansion",
    "Act 1 Scene 5: The Great Hall 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",
    "Act 2 Scene 4: A street in Verona",
    "Act 2 Scene 5: Capulet's mansion",
    "Act 2 Scene 6: Friar Lawrence's cell"
]
for scene in romeoAndJuliet {
    if scene.hasPrefix("Act 1") {
        print(scene)
    }
}
for scene in romeoAndJuliet {
    if scene.hasSuffix("Capulet's mansion") {
        print(scene)
    } else if scene.hasSuffix("Friar Lawrence's cell") {
        print(scene)
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值