字符
Swift的String类型表示特定序列的Character(字符)类型值的集合。
for character in "China".characters{
print(character)
}
//C
//h
//i
//n
//a
初始化空字符串
var myFirstString = ""
var mySecondString = String()
//以上两个字符串均为空
字符串的拼接
var str = "father"
str += " and mother"
//str现在为"father and mother"
str.appendContentsOf(" and son")
//str现在为"father and mother and son"
获取字符串的长度
let name = "wilson"
print(name.characters.count) //输出 6
提到字符串长度,想到了字符串判空操作:name.isEmpty,显然这里返回(false)
字符串比较
var str1 = "json"
let str2 = "json"
print(str.characters.elementsEqual(str2.characters))
print(str1==str2)
//以上两行代码均返回true
判断前缀或后缀
str.hasPrefix("Chi")
str.hasSuffix("na")
字符串分割
let str = "Japanese"
let a =str.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "p,n"))
print(a) //输出["Ja", "a", "ese"]
let b = str.componentsSeparatedByString("an")
print(b) //输出["Jap", "ese"]
接下来的操作都用用到字符串中最常用的两个参数:下标(index)和范围(Range),在此先提出来
let offset = str.startIndex.advancedBy(2)
let range = Range(start:str.startIndex.advancedBy(1),end:str.endIndex.advancedBy(-2))
字符串插入
var str = "Japanese"
str.insert("c",atIndex:str.endIndex.advancedBy(-1)) //插入一个字符"c"
print(str) //Japanesce
str.insertContentsOf("India".characters, at: str.startIndex.advancedBy(4))
print(str) //插入一个字符串"India",结果为:JapaIndianesce
获取字符串的子串
str.substringToIndex(offset)
str.substringFromIndex(offset)
str.substringWithRange(range)
let str = "Japanese"
let myStr=str.substringWithRange(Range(start: str.startIndex.advancedBy(3),end:str.endIndex.advancedBy(-1)))
print(myStr) //anes
字符串的删除
var str = "Japanese"
str.removeAtIndex(str.startIndex.advancedBy(1))
print(str) //Jpanese,删除一个字符"a"
str.removeRange(Range(start:str.startIndex.advancedBy(3),end:str.endIndex.advancedBy(-1)))
print(str) //Jpae,删除Jpanese中的"nes"
let str1 =String(str.characters.dropFirst(1))
print(str1) //pae,删除Jpae从头开始的1位
let str2 = String(str.characters.dropLast(3))
print(str2) //J,删除Jpae从尾开始的3位
let str3 = " welcome to China "
let a= str3.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
print(a) //welcome to China,删除头尾空白字符
let b = a.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "ona"))
print(b) //welcome to Chi,删除头尾字符集
固定位置的替换
var realName = "wilson"
realName.replaceRange(Range(start: realName.startIndex.advancedBy(1), end: realName.endIndex.advancedBy(-1)), with: "nihao")
print(realName) //wnihaon
let currentName = realName.stringByReplacingCharactersInRange(Range(start: realName.startIndex.advancedBy(1), end: realName.endIndex.advancedBy(-1)), withString: "hello")
print(currentName) //whellon,realName依然是:wnihaon
字符串反转
String(str.characters.reverse())