Swift4.0 字符串操作

import UIKit

var str = "Hello, playground"

var index = str.index(of: ",")  //得到逗号在字符串中的位置

//Swift 3.0
let greeting = str[str.startIndex ..< index!]  //得到hello
index = str.index(index!, offsetBy: 1)  //空格位置往后移动一位
let name = str[index! ..< str.endIndex]  //playground

//Swift 4.0
//得到hello
let greetings = str.prefix(upTo: index!)
let greetingss = str[..
var str = "Hello, playground"

//String 与 NSString 转换  需要遵循严格的类型转化
var strString: NSString = str as NSString
var str2: String = String(strString)

//字符串范围截取
let num = "123.45"
let deRange = num.range(of: ".")

//FIXME:按某个字符串截取

//截取小数点前字符(不包含小数点)  123
let wholeNumber = num.prefix(upTo: deRange!.lowerBound)
//截取小数点后字符(不包含小数点) 45
let backNumber = num.suffix(from: deRange!.upperBound)
//截取小数点前字符(包含小数点) 123.
let wholeNumbers = num.prefix(upTo: deRange!.upperBound)
//截取小数点后字符(包含小数点) .45
let backNumbers = num.suffix(from: deRange!.lowerBound)

//FIXME:删除字符串中的某部分  Ho
str = "Hello"
let startIndex = str.index(str.startIndex, offsetBy: 1)
let endIndex = str.index(str.startIndex, offsetBy: 3)
str.removeSubrange(startIndex...endIndex)
//替换字符串  Hnewo
var sig = "Hello"
sig.replacingCharacters(in: startIndex...endIndex, with: "new")

字符串插入
let subString = “123456”
subString.insert(Character.init("123"), at: subString.index(subString.startIndex, offsetBy: 1))  //在2后面插入123
print(subString)
 


你可能感兴趣的:(Swift4.0 字符串操作)