Swift4.0 字符串操作

来源:互联网 发布:jmeter post请求 json 编辑:程序博客网 时间:2024/05/17 18:01
import UIKitvar str = "Hello, playground"var index = str.index(of: ",")  //得到空格在字符串中的位置//Swift 3.0let greeting = str[str.startIndex ..< index!]  //得到helloindex = str.index(index!, offsetBy: 1)  //空格位置往后移动一位let name = str[index! ..< str.endIndex]  //playground//Swift 4.0//得到hellolet greetings = str.prefix(upTo: index!)let greetingss = str[..<index!]//空格位置往后移动一位index = str.index(index!, offsetBy: 1)//playgroundlet names = str.suffix(from: index!)let namess = str[index!... ]
var str = "Hello, playground"//String 与 NSString 转换  需要遵循严格的类型转化var strString: NSString = str as NSStringvar str2: String = String(strString)//字符串范围截取let num = "123.45"let deRange = num.range(of: ".")//FIXME:按某个字符串截取//截取小数点前字符(不包含小数点)  123let wholeNumber = num.prefix(upTo: deRange!.lowerBound)//截取小数点后字符(不包含小数点) 45let backNumber = num.suffix(from: deRange!.upperBound)//截取小数点前字符(包含小数点) 123.let wholeNumbers = num.prefix(upTo: deRange!.upperBound)//截取小数点后字符(包含小数点) .45let backNumbers = num.suffix(from: deRange!.lowerBound)//FIXME:删除字符串中的某部分  Hostr = "Hello"let startIndex = str.index(str.startIndex, offsetBy: 1)let endIndex = str.index(str.startIndex, offsetBy: 3)str.removeSubrange(startIndex...endIndex)//替换字符串  Hnewovar sig = "Hello"sig.replacingCharacters(in: startIndex...endIndex, with: "new")