1.字符串定义
var s = "aaaaaa"
//两个字符串均为空并等价。 varemptyString="" varanotherEmptyString=String()
字符串字面量可以包含以下特殊字符:转义字符\0
(空字符)、\\
(反斜线)、\t
(水平制表符)、\n
(换行符)、\r
(回车符)、\"
(双引号)、\'
(单引号)。
2.字符串拼接
//字符串拼接 varx="x" vary="y" varz=x+y varm=z+"m" varn="n"n+=m//使用\()完成字符串的插值 varresult="\(x)==\(y)==\(z)==\(m)==\(n)" println(result) letplus1=s1+c1
3.字符串遍历
varmyString="Thisisastring" forcharacterinmyString { println(character) }
4.字符个数统计
varmyString="Hereismystring,letscountthecharacters!" println(count(myString))
5.字符串比较 & 是否包含前后缀
varcheck1:String="Swiftisgood!" varcheck2:String="Swiftisgood!" //字符串是否相等 ifcheck1==check2 { println("check1=check2") } else {println("check1!=check2") } //是否包含前缀 varpreCheck="Swift"ifcheck1.hasPrefix(preCheck){println("包含前缀")} //是否包含后缀 varsufCheck="good!" ifcheck1.hasSuffix(sufCheck) { println("包含后缀") }
6.大小写转换
letmyString="Waitamoment,please." letnewString=myString.uppercaseString letmyString="Waitamoment,please." letnewString=myString.lowercaseString
7.字符串是否包含其他字符串
varmyString="Thisisastringtest" ifmyString.rangeOfString("test") { println("exists") }
8.字符串截取
//截取字符串的标识位从1开始计数 letmyString="ABCDEFGHI" //1.从目标标识位后一个字符开始截取余下的字符串 letmySubstring=(myString.substringFromIndex(2)) println(mySubstring) letmySubstring2=(myString.substringToIndex(4)) println(mySubstring2)
9.字符串去空格
varmyString="Let'strimthewhitespace" varnewString=myString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
10.字符串分割为字符串数组
//单一分隔符:只有一种分割符 varmyString="Berlin,Paris,NewYork,SanFrancisco" //1.隐式定义字符串数组 varmyArray=myString.componentsSeparatedByString(",") //2.显示定义字符串数组 varmyArray2:String[]=myString.componentsSeparatedByString(",") foreminmyArray2{ print(em) } //多重分割符:有2个或两个以上分隔符 varmyString2="One-Two-Three-123" vararray2:String[]=myString2.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString:"-")) //["One","Two","Three","1","2","3"]
11.字符串转换为NSData
letmyString="Stringtoencode" letstring:NSString=myString letdata=string.dataUsingEncoding(NSUTF8StringEncoding)原文链接:https://www.f2er.com/swift/326131.html