在之前我就写过一篇文章关于可以插入字符的文章23.使用Swift自带的join函数拼接字符串,这里讲的是使用join函数在每个字符之间插入自定义的字符.
1.获取字符串的索引
let sayHello = "Hello word!"
// 开始的characters字符,输出的结果为: H
print(sayHello[sayHello.startIndex])
// 结尾的characters字符,输出的结果为: !
print(sayHello[sayHello.endIndex.predecessor()])
// 第7个characters的字符,输出的结果为: o
print(sayHello[sayHello.startIndex.advancedBy(7)])
// 遍历sayHello的characters的索引范围,输出的结果为: H-e-l-l-o- -w-o-r-d-!-
for index in sayHello.characters.indices {
// 在每个索引字符后面添加一个字符
print("\(sayHello[index])",terminator: "-")
}
2.插入和删除字符
var welcome = "hello"
// 插入字符"!"到welcome最后的索引
welcome.insert("!",atIndex: welcome.endIndex)
print(welcome)
// 插入字符" wrod"在welcome最后的索引前一个
welcome.insertContentsOf(" word".characters,at: welcome.endIndex.predecessor())
print(welcome)
// 删除在welcome最后的索引前一个
welcome.removeAtIndex(welcome.endIndex.predecessor())
print(welcome)
// 删除规定范围内的字符
let range = welcome.endIndex.advancedBy(-5) ..< welcome.endIndex
welcome.removeRange(range)
print(welcome)
输出结果
3.判断字符
在Swift当中有分为三种对比,字符内容相等,字符后缀相等,字符后缀相等.
字符内容判断
let hello = "hello"
let hi = "hello"
if hello == hi {
print("These two strings are considered equal")
}
字符前缀判断
let personName = [
"person name 1 : xiaoming","person name 2 : honghong","person name 3 : zhangsan","person name 4 : lisi","person name 5 : huangwu","person name 6 : datou"
]
var personNumber = 0
for name in personName {
if name.hasPrefix("person") {
++personNumber
}
}
print(personNumber)
// 输出的结果为: 6
字符串后缀判断
let personLastName = [
"xiaoming chen","xiaohong chen","zhangsan li","baibai chen"
]
var personLastNameNumber = 0
for lastName in personLastName {
if lastName.hasSuffix("chen") {
++personLastNameNumber
}
}
print(personLastNameNumber)
// 输出结果为: 3
好了,这次就讲到这里,谢谢