Language Guide --- Strings and Characters

String and Characters

String Literals

let someString = "some value literal value"

Multiline String Literals

let quotation = """
The White Rabbit put on his spectacles.  "Where shall I begin,
please your Majesty?" he asked.
 
"Begin at the beginning," the King said gravely, "and go on
till you come to the end; then stop."
"""

多行字符串包含两个 '''''' 之间的所有内容。
如果在多行string中使用换行符只是为了方便读,并不打算在string串中包含换行,可以在行结尾处使用\。

let softWrappedQuotation = """
The White Rabbit put on his spectacles.  "Where shall I begin, \
please your Majesty?" he asked.
 
"Begin at the beginning," the King said gravely, "and go on \
till you come to the end; then stop."
"""

Strings Are Value Types

swift中的string是值类型的,如果你创建了一个string,把它当作参数传给了函数或者方法,参数是string的拷贝。

Working with Characters

可以从string中遍历得到一个一个的字符。

for character in "Dog!🐶" {
    print(character)
}

你也可以声明一个Character类型的常量或者变量,使用单个字符的string字面量。

let exclamationMark: Character = "!"

可以使用一组字符,作为string构造方法的参数来创建string。

let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString)
// Prints "Cat!🐱"

Concatenating Strings and Characters

let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"

当连接多行字符串的时候,swift不会自动加换行。

let badStart = """
one
two
"""
let end = """
three
"""
print(badStart + end)
// one
// twothree
 
let goodStart = """
one
two
 
"""
print(goodStart + end)
// one
// two
// three

Accessing and Modifying a String

使用startIndex属性获取String中的第一字符。endIndex表示的是String最后一个字符的后一个位置。所以,endIndex不是一个有效的string下标。如果String为空,startIndexendIndex相等。

使用index(before:)index(after:)方法获得指定索引之前和之后的索引。使用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

使用string的indices获取string中每个字符的索引。

for index in greeting.indices {
    print("\(greeting[index]) ", terminator: "")
}

startIndexendIndex属性、index(before:)index(after:)index(_:offsetBy:)方法可以用在任何遵守Collection协议的类型上。例如:Array、Dictionary、Set。

Inserting and Removing

使用insert(_:at:)方法插入字符,使用insert(contentsOf:at:)插入字符串。

var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome now equals "hello!"
 
welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there!"

使用remove(at:)方法删除字符,使用removeSubrang:(_:)方法删除字串。

welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there"
 
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome now equals "hello"

这些insert和remve方法可以用在遵守RangeReplaceableCollection协议的对象上,例如Array、Dictionary、Set。

Substrings

如果从一个string取得字串,例如使用下表或者像prefix(_:)这样的方法,得到的结果是一个Substring类型。在swift中,Substring几乎有String的所有方法,这就意味着可以像操作String那样使用Substring。如果你只是临时地使用字串,使用Substring就可以了;如果你要长时间使用这个字串,就要把它转为String 类型了。例如:

let greeting = "Hello, world!"
let index = greeting.index(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning is "Hello"
 
// Convert the result to a String for long-term storage.
let newString = String(beginning)

作为优化,Substring可以重用String的内存。如果Substring长时间在使用,那么String的内存就必须等到Substring不再使用了才能释放。所以如果要长时间使用Substring就要转成String了。

Comparing Strings

String and Character Equality

使用 == 比较字符串或者字符是或否相等,使用!=比较字符串或者字符是否不相等。

Prefix and Suffix Equality

使用hasPrefix(_:)hasSuffix(_:)检查字符串是否包含指定字符串的前缀和后缀。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容