swift - 字符串操作(替换、过滤、去掉空格、分割、拼接、字符串截取)

    let s = " / 2 3 4 ? / "
    // 替换
    print("空格替换成-:", s.replacingOccurrences(of: " ", with: "-"))
    // 过滤
    print("空格过滤掉:", s.replacingOccurrences(of: " ", with: ""))
    // 去首尾空格
    print("去掉空格:", s.trimmingCharacters(in: .whitespaces))
    // 分割
    print("分割:", s.components(separatedBy: "/"))
    // 拼接
    let a = ["1", "2", "3"]
    print("拼接:", a.joined(separator: "-"))

字符串截取:

let timeString = "2016.12.12"
        
let timeString = "2016.12.12"

let index = timeString.index(timeString.endIndex, offsetBy: -2)
let suffix = timeString.substring(from: index)

let index1 = timeString.index(timeString.startIndex, offsetBy: 2)
let prefix = timeString.substring(to: index1)

let startRange = timeString.index(timeString.startIndex, offsetBy: 5)
let endRange = timeString.index(timeString.startIndex, offsetBy: 7)
let middle = timeString.substring(with: Range(startRange..(start: startIndex, end: endIndex)
swift3.0改变为:
let range = Range(startIndex..

Range使用举例:

左到右截取
startIndex to offsetBy正数
右到左截取
endindex from offsetBy负数
func ga_dateToDay() -> String {
    
    let index = self.index(self.endIndex, offsetBy: -2)
    let suffix = self.substring(from: index)
    // substring(to: index)
    
    let startRange = self.index(self.startIndex, offsetBy: 5)
    let endRange = self.index(self.startIndex, offsetBy: 7)
    let middle = self.substring(with: Range(startRange.. suffixInt! {
            if day! - suffixInt! == 1 {
                return "昨天"
            }
            return self
        }
    } else {
        if month! - middleInt! == 1 {
            if day == 1 {
                return "昨天"
            }
        }
    }
    
    return self
}

你可能感兴趣的:(swift - 字符串操作(替换、过滤、去掉空格、分割、拼接、字符串截取))