1.判断是否是空值
//判断是否是空值
let str:String = ""
if str.isEmpty{
print("str is nil")
}
打印结果:str is nil
let str1:String = "hahahaha"
if str1.isEmpty{
print("str is nil")
}else{
print("str is \( str1)")
}
打印结果:str is hahahaha
//获取字符数量
let str:String = "http://www.baidu.com"
print("the num is \( str.characters.count)")
打印结果:the num is 20
3.遍历字符
//遍历字符
let str:String = "http://www.baidu.com"
for charvalue in str.characters{
print("--->\(charvalue)")
}
打印结果:
--->h --->t --->t --->p --->: --->/ --->/ --->w --->w --->w --->. --->b --->a --->i --->d --->u --->. --->c --->o --->m
4.字符串是否有特定前缀/后缀
//字符串是否有前后
let str:String = "http://www.baidu.com"
if str .hasPrefix("http://"){
print("hasPrefix--->http://")
}
if str .hasSuffix(".com"){
print("hasSuffix--->.com")
}
打印结果:
hasPrefix--->http://
hasSuffix--->.com
5.大小写转换
//大小写转换
let str = "Hello World!"
//大写
let uppercase = str.uppercaseString
//小写
let lowercase = str.lowercaseString
//首字母大写
let capitalized = str.capitalizedString
print("uppercase--->\(uppercase)")
print("lowercase--->\(lowercase)")
print("capitalized--->\(capitalized)")
打印结果:
uppercase--->HELLO WORLD!
lowercase--->hello world!
capitalized--->Hello World!
6.字符串数组
// 字符串数组
var strArray = [String]()
strArray.append("hello")
strArray.append(" ")
strArray.append("world!")
print("strArray--->\(strArray)")
//拼接字符串
print("strArray--->\(strArray.joinWithSeparator(""))")
//拆分字符串
let newArray = strArray.split("")
print("strArray--->\(newArray)")
打印结果:
strArray--->["hello"," ","world!"]
strArray--->hello world!
strArray--->[[ArraySlice(["hello","world!"])]]
7.字符数组删除
//字符数组删除
var strArray = ["hello","world","!"]
print("strArray--->\(strArray)")
//删除第一个
strArray.removeFirst()
print("strArray--->\(strArray)")
//删除最后一个
strArray.removeLast()
print("strArray--->\(strArray)")
//删除指定下标的元素
strArray .removeAtIndex(0)
print("strArray--->\(strArray)")
//删除所有元素
strArray .removeAll()
print("strArray--->\(strArray)")
打印结果:
strArray--->["hello","!"]
strArray--->[" ","world"]
strArray--->["world"]
strArray--->[]