自己學(xué)習(xí)整理的一些字符串的用法:
//字符串的初始化
var str:String = "hellow Swift"
var str2 = "222"
//字符串的拼接和格式化
str += str2
let number = 100
let name = "你剛回來(lái)了"
//拼接其他類(lèi)型
var str3:String = "name = \(name),age = \(number)"
//oc形式的拼接方法
var str4 = String(format: "%@,%@", arguments: ["xiao","ming"])
//字符串額截榷涸浴(字符串和oc的字符串可以無(wú)縫連接)
//裝換oc的字符串可以使用oc的一些截取的方法
var str5:NSString = "你剛回來(lái)了"
var str6 = "你剛回來(lái)了" as NSString
var substr = str6.substringWithRange(NSMakeRange(0, 4))
//swift的字符的截取
var str7 = "你剛回來(lái)了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)
//從什么地方開(kāi)始截妊晷铡(從index開(kāi)始侍咱,不包含index的字符)
var subStr1 = str7.substringFromIndex(index);
//從0開(kāi)始截取 到字符串中長(zhǎng)度的減6的位置結(jié)束(不包含index2)
var subStr2 = str7.substringToIndex(index2);
//從index的位置到index2的位置(不包含index和index2的位置)
var substr3 = str7.substringWithRange(range);
//遍歷字符
for c in str4.characters
{
print(c)
}
在swift4之后substring的方法被廢除
只能使用以下方式自己實(shí)現(xiàn)
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個(gè)位置取一個(gè)字符
let index = str.index(str.startIndex, offsetBy: 7)
print(str[index]) // p
// range 從7個(gè)開(kāi)始到末尾倒數(shù)4個(gè)
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
print(str[range]) // play
//從開(kāi)始取5個(gè)字符
let mySubstring = str.prefix(5)
print(mySubstring) // Hello
//末尾取10個(gè)字符
let mySubstring1 = str.suffix(10)
print(mySubstring1) // playground
實(shí)例:實(shí)現(xiàn)獲取子字符串
從第幾個(gè)字符開(kāi)始舍悯,取幾個(gè)字符
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))