Swift

Swift 5.x String常用api

2020-06-25  本文已影响0人  ShenYj

1. 遍历字符串获取每个字符

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

输出结果:

D
o
g
!

2. 字符串拼接

let hello = "hello"
let world = "world"
let helloWorld = hello + " " + world
print(helloWorld)

输出结果:

hello world
var hello = "hello"
let world = "world"
hello += world
print(hello)

输出结果:

helloworld
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. 字符串插值

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

4. 字符串索引

注: 并不是字符串下标脚本的合法实际参数
注: 如果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

5. 字符串插入

var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
print(welcome)

输出结果:

hello!
var welcome = "hello"
welcome.insert(contentsOf: " world!", at: welcome.endIndex)
print(welcome)

输出结果:

hello world!

6. 字符串删除

var welcome = "welcome!"
welcome.remove(at: welcome.index(before: welcome.endIndex))
print(welcome)

输出结果:

welcome
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

7. 字符串子串

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!

8. 字符串比较

var helloWorld = "Hello, world!"
print(helloWorld.hasPrefix("Hello"))
print(helloWorld.hasSuffix("world!"))

输出结果:

true
true
上一篇 下一篇

猜你喜欢

热点阅读