Swift 5.x String常用api - ShenYj/ShenYj.github.io GitHub Wiki
-
for-in循环遍历String中的每一个独立的Character
for character in "Dog!" {
print(character)
}输出结果:
D
o
g
!- 2.1 使用加运算符(
+)创建新字符串
let hello = "hello"
let world = "world"
let helloWorld = hello + " " + world
print(helloWorld)输出结果:
hello world- 2.2 使用加赋值符号(
+=)在已存在的String值末尾追加一个String值
var hello = "hello"
let world = "world"
hello += world
print(hello)输出结果:
helloworld- 2.3 使用
String类型的append()方法来给一个String变量的末尾追加Character值
var hello1 = "hello"
var hello2 = hello1
print("hello1:" + hello1)
print("hello2:" + hello2)
hello2.append("!")
print("hello1:" + hello1)
print("hello2:" + hello2)输出结果:
hello1:hello
hello2:hello
hello1:hello
hello2:hello!-
3.1 字符串插值是一种从混合常量、变量、字面量和表达式的字符串字面量构造新
String值的方法 -
3.2 每一个插入到字符串字面量的元素都要被一对圆括号包裹, 然后使用反斜杠前缀:
\(插入元素) -
3.3 类似于
NSString的stringWithFormat方法, 但是更加简便, 更强大
e.g.
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
print(message)输出结果:
3 times 2.5 is 7.5-
startIndexString中第一个Character的位置 -
endIndexString中__最后一个字符后__的位置 - 使用
index(before:)和index(after:)方法来访问给定索引的前后 - 要访问给定索引更远的索引, 可以使用
index(_:offsetBy:) - 使用
indices属性来访问字符串中每个字符的索引
注: 并不是字符串下标脚本的合法实际参数
注: 如果String为空, 则startIndex与endIndex相等
注: String.Index 相当于每个Character在字符串中的位置
e.g.
var str = "Hello world!"
print("第一个元素: \(str[str.startIndex])")
print("最后一个元素: \(str[str.index(before: str.endIndex)])")
print("索引6的元素: \(str[str.index(str.startIndex, offsetBy: 6)])")输出结果:
第一个元素: H
最后一个元素: !
索引6的元素: w- 插入字符, 使用
insert(_:at:)方法
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
print(welcome)输出结果:
hello!- 插入另一个字符串的内容到特定的索引, 使用
insert(contentsOf:at:)方法
var welcome = "hello"
welcome.insert(contentsOf: " world!", at: welcome.endIndex)
print(welcome)输出结果:
hello world!- 移除字符, 使用
remove(at:)方法
var welcome = "welcome!"
welcome.remove(at: welcome.index(before: welcome.endIndex))
print(welcome)输出结果:
welcome- 移除一小段特定范围的字符串, 使用
removeSubrange(_:)方法
var welcome = "welcome!"
let startIndex = welcome.index(welcome.startIndex, offsetBy: 2)
let endIndex = welcome.index(before: welcome.endIndex)
welcome.removeSubrange(startIndex...endIndex)
print(welcome)输出结果:
we- 使用下表或者类似
prefix(_:)方法得到的子字符串是Substring类型 -
Substring拥有String的大部分方法 -
Substring可以转成String类型
var helloWorld = "Hello, world!"
let index = helloWorld.firstIndex(of: ",") ?? helloWorld.endIndex
let prefix = helloWorld[..<index]
let subfix = helloWorld[index...helloWorld.index(before: helloWorld.endIndex)]
print(prefix)
print(subfix)输出结果:
Hello
, world!- 字符串和字符串相等性
==和!= - 前缀相当性
hasPrefix(_:) - 后缀相等性
hasSuffix(_:)
var helloWorld = "Hello, world!"
print(helloWorld.hasPrefix("Hello"))
print(helloWorld.hasSuffix("world!"))输出结果:
true
true