swift-字符串的使用

var str = “hello, swift”

let startIndex = str.startIndex
startIndex
str[startIndex]

str[startIndex.advancedBy(5)]

let spaceIndex = startIndex.advancedBy(6)

spaceIndex
str[spaceIndex]
//指获得当前索引的前一个位置
str[spaceIndex.predecessor()]
//指获得当前索引的后一个位置
str[spaceIndex.successor()]

//一个字符串结束位置的索引
let endIndex = str.endIndex
//[startIndex,endIndex)
str[endIndex.predecessor()]//最后一个字符

str[startIndex..<spaceIndex]

let range = startIndex..<spaceIndex.predecessor()
str.replaceRange(range, with: “hi”)

//添加字符串
str.appendContentsOf(“!!!”)
//插入字符串
str.insert(“?”, atIndex: str.endIndex)
//移除一个字符串
str.removeAtIndex(str.endIndex.predecessor())

str.removeRange(str.endIndex.advancedBy(-2)..<str.endIndex)
str.uppercaseString//大写
str.lowercaseString//小写
str.capitalizedString

str.containsString(“hello”)//包含子串
str.hasPrefix(“he”)//前缀
str.hasPrefix(“ft”)//后缀

var s3:NSString = “one third is 0.33”
s3.substringFromIndex(4)
s3.substringToIndex(3)

s3.substringWithRange(NSMakeRange(4,5))//从第4个位置开始,长度为5的字符串
let s6 = ”      hello     “asNSString
//截取字符串中的空格
s6.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString:” “))

发表评论

电子邮件地址不会被公开。 必填项已用*标注