自己学习整理的一些字符串的用法:
//字符串的初始化
var str:String = "hellow Swift"
var str2 = "222"
//字符串的拼接和格式化
str += str2
let number = 100
let name = "你刚回来了"
//拼接其他类型
var str3:String = "name = \(name),age = \(number)"
//oc形式的拼接方法
var str4 = String(format: "%@,%@", arguments: ["xiao","ming"])
//字符串额截取(字符串和oc的字符串可以无缝连接)
//装换oc的字符串可以使用oc的一些截取的方法
var str5:NSString = "你刚回来了"
var str6 = "你刚回来了" as NSString
var substr = str6.substringWithRange(NSMakeRange(0, 4))
//swift的字符的截取
var str7 = "你刚回来了234567890"
// let index = advance(s.startIndex, 5) swift 1.x
//let index2 = advance(s.endIndex, -6); swift 1.x
let index = str7.startIndex.advancedBy(5) //swift 2.0+
let index2 = str7.endIndex.advancedBy(-2) //swift 2.0+
var range = Range<String.Index>(start: index,end: index2)
//从什么地方开始截取(从index开始,不包含index的字符)
var subStr1 = str7.substringFromIndex(index);
//从0开始截取 到字符串中长度的减6的位置结束(不包含index2)
var subStr2 = str7.substringToIndex(index2);
//从index的位置到index2的位置(不包含index和index2的位置)
var substr3 = str7.substringWithRange(range);
//遍历字符
for c in str4.characters
{
print(c)
}
在swift4之后substring的方法被废除
只能使用以下方式自己实现
swift5
let str = "Hello, playgroud"
// character
let index = str.index(before: str.endIndex)
print(str[index]) // d
// range
let range = str.startIndex..<str.index(before: str.endIndex)
print(str[range]) // Hello, playgroud
let str = "Hello, playgroud"
// character 从第7个位置取一个字符
let index = str.index(str.startIndex, offsetBy: 7)
print(str[index]) // p
// range 从7个开始到末尾倒数4个
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
print(str[range]) // play
//从开始取5个字符
let mySubstring = str.prefix(5)
print(mySubstring) // Hello
//末尾取10个字符
let mySubstring1 = str.suffix(10)
print(mySubstring1) // playground
实例:实现获取子字符串
从第几个字符开始,取几个字符
extension String {
/// substring
///
/// - Parameters:
/// - fromPoint: start point
/// - offset: from start point get string lenth
/// - Returns: string
func wm_substring(from fromPoint:Int,lenth offset:Int) -> String {
let sIndex = self.index(self.startIndex, offsetBy:fromPoint - 1)
guard let index = self.index(sIndex, offsetBy: offset, limitedBy: self.endIndex) else { return "" }
return String(self[index])
}
}
使用
let str = "1233dfdsadads"
print(str.wm_substring(from: 3, lenth: 1))