Swift3.0字符串相关操作
以下有关字符串的常用操作都可直接复制到Xcode中进行验证,如发现错误,请在评论区留言指正!
1.字符串的定义
var str1="hello, swift." //字符串变量 相当于OC中的可变字符串
let str2="hello, swift." //字符串常量 相当于OC中的不可变字符串
let str3="" //空字符串
let str4=String() //空字符串
2.字符串的连接
2.1 使用+连接符
//字符串的连接
let str1 = "hello"
let str2 = "swift"
let str3 = str1 + str2
print(str3)
2.2 使用字符串插值(该方法也可用于字符串与其他类型值的连接)
let str1 = "hello"
let str2 = "swift"
let str4 = "\(str1)\(str2)"
print(str4)
3.字符串枚举字符
let str="伊丽莎白"
for ch in str.characters{
print(ch)
}
4.字符串长度
//字符串的长度
let str1 = "hello swift"
print(str1.characters.count)
5.字符串的比较
//字符串的比较 判断两个字符串是否相等
let str1 = "hello"
let str2 = "hello"
if str1 == str2{
print("两个字符串是相等的")
}else{
print("两个字符串不相等")
}
6.判断是否包含子串
//判断字符串是否包含子串
let str1 = "hello swift"
let str2 = "SWIFT"
let lmrRange = str1.range(of: str2)//正向查找
let rmlRange = str1.range(of: str2, options: .backwards)//反向查找
let ignore_Text_transformRange = str1.range(of:str2, options: .caseInsensitive, range:nil , locale:nil)//忽略大小写
if ignore_Text_transformRange != nil{
print("str1中包含着子串")
}else{
print("str1中不包含子串")
}
7.首字母大写capitalized
//首字母大写
let str1 = "hello"
let str2 = str1.capitalized
print(str2)
8.字符串全部转为大写uppercase
//字符串转为大写
let str1 = "hello"
let str2 = str1.uppercased()
print(str2)
9.字符串全部转为小写lowrecase
//字符串转为小写
let str1 = "HELLO"
let str2 = str1.lowercased()
print(str2)
10.按照下标截取子字符串
//字符串截取子字符串
let str1 = "HELLO swift"
let str2 = str1.substring(from: str1.startIndex)//从头开始截取
let str3 = str1.substring(to: str1.endIndex)//截取到尾部
//获取截取范围
let i = str1.index(str1.startIndex, offsetBy: 4)
let j = str1.index(str1.startIndex, offsetBy: 8)
let str4 = str1.substring(with: i..<j)
print(str2)
print(str3)
print(str4)
11.字符串修整trim
var str1 = " !hi? !23? !???"
let str2 = str1.trimmingCharacters(in: NSCharacterSet.whitespaces)//"!hi !23 !"去掉两边的空格
let str3 = str2.trimmingCharacters(in: NSCharacterSet(charactersIn:"!?") as CharacterSet)//"hi !23" 去掉两边的空格和‘!’ ,把 字符串中的每个字符进行了分解并去除
print(str3)
注意:这里是只能修整两边的,只能修整两边的
12.字符串分解split
//字符串的分解split
var str1 = "hello,swift,you,change,so,fast,!"
let strArray1:[String] = str1.components(separatedBy: ",")
for index in strArray1{
print(index)
}
var str2 = "hello,swift?goodbye,swift?!"
let strArray2:[String] = str2.components(separatedBy: NSCharacterSet(charactersIn:",?") as CharacterSet)
for index in strArray2{
print(index)
}
13.字符串替换replace
//字符串替换replace
var str1 = "hello Object-C,you change so fast!"
let str2 = str1.replacingOccurrences(of: "Object-C", with: "swift")//字符串替换字符串
let i = str1.index(str1.startIndex, offsetBy: 6)
let j = str1.index(str1.startIndex, offsetBy: 14)
let str3 = str1.replacingCharacters(in: i..<j), with: "swift")//字符串替换某个范围的字符串
let str4 = str1.replacingOccurrences(of: "OBJECt-C", with: "SWIFT", options: .caseInsensitive, range: nil)//忽略大小写替换
print(str2)
print(str3)
print(str4)