Swift String字符串操作

var str1 = "Hello Swift!"

// 取第一个字符 'H'
str1.first

// 取前两个字符
let he_index = str1.index(str1.startIndex, offsetBy: 2)
let he = str1[..<he_index]

// 去掉前两个字符
let lloSwift = str1[he_index..<str1.endIndex]

// 取最后一个字符 '!'
str1.last

// 取最后两个字符 '!'
let ts_index = str1.index(str1.endIndex, offsetBy: -2)
let ts = str1[ts_index..<str1.endIndex]

// 去掉后两个字符
let helloSwif = str1[..<ts_index]

// 取'el'
let h_index = str1.index(str1.startIndex, offsetBy: 1)
let el_index = str1.index(h_index, offsetBy: 2)
let el = str1[h_index..<el_index]

// 把Swift换成Objective-C
if let s_index = str1.index(of: "S") {
    if let symbol_index = str1.index(of: "!") {
        str1.replaceSubrange(s_index..<symbol_index, with: "Objective-C")
    }
}

// 分割字符串 Hello Swift
str1 = "Hello Swift!"
let split = str1.split(separator: " ")
String(split[0])

猜你喜欢

转载自my.oschina.net/u/3795484/blog/1633414