Swift:字符串范围截取操作

1.contains方法应用:

let str1 = "josh"
let str2 = "joshwang"
str1.contains(str2)   //false
str2.contains(str1)   //true

2.append方法应用:

var resultArray: [String] = []
resultArray.append(contentsOf: [str1, str2,"123456"])
resultArray.append("hahahaha")
print(resultArray)

输出结果:["josh", "joshwang", "123456", "hahahaha"]

3.字符串范围截取操作

var str = "Hello, joshwang0830"

var index = str.index(of: ",")//得到“,”在字符串中的位置
let str3 = str[index!...]//获取","后的所有字符(包括",")

//Swift 3.0
let greeting = str[str.startIndex..

4.String 与 NSString 转换  需要遵循严格的类型转化

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

5.字符串范围截取(prefix;suffix):

//字符串范围截取
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)

6.删除与字符串替换

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

你可能感兴趣的:(Swift,字符串截取,经验,ios开发,字符串操作)