Swift String通过下标获取子串、计算字符串的宽高、16进制转10进制、String转换为AttributedString、使用正则验证合法性

String通过下标获取子串

extension String {
    func index(_ offset: Int) -> Index {
        return self.index(startIndex, offsetBy: offset)
    }
    func substring(from: Int) -> String {
        let fromIndex = index(from)
        return String(self[fromIndex...])
    }
    func substring(to: Int) -> String {
        let toIndex = index(to)
        return String(self[.. String {
        let startIndex = index(start)
        let endIndex = index(end)
        return String(self[startIndex..

计算字符串的宽高
16进制转10进制
String转换为AttributedString

import Foundation

extension String {
    
    public func calcuateLabSizeWidth(font: UIFont, maxHeight: CGFloat) -> CGFloat {
        let attributes = [kCTFontAttributeName: font]
        let norStr = NSString(string: self)
        let size = norStr.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: maxHeight), options: .usesLineFragmentOrigin, attributes: attributes as [NSAttributedStringKey : Any], context: nil)
        return size.width
    }
    
    public func calcuateLabSizeHeight(font: UIFont, maxWidth: CGFloat) -> CGFloat {
        let attributes = [kCTFontAttributeName: font]
        let norStr = NSString(string: self)
        let size = norStr.boundingRect(with: CGSize(width: maxWidth, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: attributes as [NSAttributedStringKey : Any], context: nil)
        return size.height
    }

    public func transform16To10() -> Int {
        var num = self
        if num.hasPrefix("0x") || num.hasPrefix("0X") {
            num.remove(at: num.index(from: 1))
        }
        let str = num.uppercased()
        var sum = 0
        for i in str.utf8 {
            sum = sum * 16 + Int(i) - 48
            if i >= 65 {
                sum -= 7
            }
        }
        return sum
    }
    
    public func toAttributedString(color: UIColor = .white) -> NSMutableAttributedString {
        let str = NSMutableAttributedString(string: self)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 5
        let dic: Dictionary = [NSAttributedStringKey.foregroundColor: color,
                                 NSAttributedStringKey.paragraphStyle: paragraphStyle];
        str.setAttributes(dic, range: NSMakeRange(0, self.count))
        return str
    }

}

使用正则验证字符串的合法性(也可以定义成属性的形式)

extension String {
    func isLegalNickName() -> Bool {
        let pattern = "^[A-Za-z][A-Za-z0-9]*$"
        return NSPredicate(format: "SELF MATCHES %@", pattern).evaluate(with: self)
    }
    func isPasswordString() -> Bool {
        let pattern = "^[0-9]*$"
        return NSPredicate(format: "SELF MATCHES %@", pattern).evaluate(with: self)
    }
    func isNumberString() -> Bool {
        let pattern = "^[0-9.]*$"
        return NSPredicate(format: "SELF MATCHES %@", pattern).evaluate(with: self)
    }
}

URL参数解析

extension String {
    func containsParam(key: String) -> Bool {
        return getUrlStringParam(paramKey: key) == "" ? false : true
    }
    private func getUrlStringParam(paramKey: String) -> String {
        guard let params = self.components(separatedBy: "?").last else {
            return ""
        }
        var paramValue = ""
        params.components(separatedBy: "&").forEach { (para) in
            if let key = para.components(separatedBy: "=").first,
                let value = para.components(separatedBy: "=").last,
                key == paramKey {
                paramValue = value
            }
        }
        return paramValue
    }
}

你可能感兴趣的:(Swift)