swift常用字符串操作

// 字符串的使用

for i in 0..<10{

print(i)

}

for _ in 0...10 {

print("for 循环")

}

// 字符串遍历

let str = "shuxi"

for c in str.characters {

print(c )

}

// 字符串拼接

letstr1 = "xiao gang"

let str2 = "shuxi"

let str3 = str1 + str2

print(str3)

// 字符串与其他标识符的拼接

let name = "hxg"

let age = 20

let height = 1.80

let info = "my name is \(name) age is \(age) height is \(height)"

// 拼接字符串时,字符串的格式化,数字格式化成字符串

let second = 18

let min = 2

let timgStr = String(format:"%.2d:%.2d",arguments:[min,second])

// 字符串截取

let urlStr = "www.baidu.com"

//先将string类型转为NSString类型

//1. 获取.号的索引位置

let index = urlStr.index(str.startIndex,offsetBy:3)

let res = urlStr.substring(to: index)

//2. 截取某个索引位置之后的所有的字符串

let lastRes = urlStr.substring(from: index)

//3.截取某个位置开始长度为N的字符串

let startIndex = urlStr.index(urlStr.startIndex, offsetBy: 3)

let endIndex = urlStr.index(startIndex, offsetBy:2)

let midRes = urlStr.substring(with: startIndex..

// 字符串截取的另一种写法

let head = (urlStr as NSString).substring(to:2)

let mid = (urlStr as NSString).substring(with: NSMakeRange(2,1))

let foot = (urlStr as NSString).substring(to:5)

你可能感兴趣的:(swift常用字符串操作)