1.移除一段特定的字符串

 var str = "Hello word!"
 let range = str.index(str.startIndex, offsetBy: 5)..<str.endIndex
 str.removeSubrange(range) 
 print(str)  // 输出:Hello

2.插入一个字符串

 var str = "Hello!"
 str.insert(contentsOf:"world", at: str.index(before: str.endIndex))
 print(str) // Helloworld

3.替换字符串

 //字符串替换 (写在String扩展里)
  func replace(of: String, with: String) -> String {
    return self.replacingOccurrences(of: of, with: with)
  }
  let greeting = "Hello,world"
  let str = greeting.replace(of: "world", with: "jesse")
  print(str) //Hello,jesse

4.给String类添加下标脚本支持索引访问(写在String类扩展里)

 extension String
{
    subscript(start:Int, length:Int) -> String
        {
        get{
            let index1 = self.index(self.startIndex, offsetBy: start)
            let index2 = self.index(index1, offsetBy: length)
            return String(self[index1..<index2])
        }
        set{
            let tmp = self
            var s = ""
            var e = ""
            for (idx, item) in tmp.enumerated() {
                if(idx < start)
                {
                    s += "(item)"
                }
                if(idx >= start + length)
                {
                    e += "(item)"
                }
            }
            self = s + newValue + e
        }
    }
    subscript(index:Int) -> String
        {
        get{
            return String(self[self.index(self.startIndex, offsetBy: index)])
        }
        set{
            let tmp = self
            self = ""
            for (idx, item) in tmp.enumerated() {
                if idx == index {
                    self += "(newValue)"
                }else{
                    self += "(item)"
                }
            }
        }
    }
}

使用案例

var greeting = "Hello, world!"
let subStr = greeting[2,3]
print(subStr)//打印结果为:llo
greeting[2,3] = "222"
print(greeting)//打印结果为:He222, world!
print(greeting[3])//打印结果为:2

5.多行字面量:使用三个双引号(“””)包裹

  let str = """
           12345
           234567
           3456789
           """
  print(str)

打印结果

12345
234567
3456789

6.字符串切割拆分

     let str = "Hello,world"
     print(str.split(separator: ","))
     //打印结果
     //["Hello", "world"]

7.判断字符串是否是整数(写在类扩展中)

  func isPureInt() -> Bool {
        let scan = Scanner(string: self)
        var val = 0
        let boolValue = scan.scanInt(&amp;val) &amp;&amp; scan.isAtEnd
        return boolValue
  }

使用案例

 let str = "Hello,world"
 print(str.isPureInt())  //false
 let str1 = "123"
 print(str1.isPureInt()) //true

8.给时间减1分钟

   static func reduceOneSecond(time:String) -> String {
        let t = String.formatDate(Date(), "yyyy-MM-dd")
        let tempdate = String.dateWithFormat(string: t + " (time)", format: "yyyy-MM-dd HH:mm")
        guard let date =  tempdate?.addingTimeInterval(-60) else { return "(t) (time)"  }
        return String.formatDate(date, "HH:mm")
    }
 

9. 计算文字宽度

    static func textWidth(text:String) -> CGFloat {
        let length = text.boundingRect(with:CGSize(width:CGFloat(kScreenWidth - 30), height: 30), options: .usesLineFragmentOrigin, attributes: [.font:UIFont.systemFont(ofSize: 15)], context:nil).size.width + 30
        if length >= CGFloat(kScreenWidth - 30){
            return CGFloat(kScreenWidth - 30)
        }else{
            return length
        }
    }

10. 计算文字高度

   func textHeight(font:UIFont,width:CGFloat) -> CGFloat {
        let height = self.boundingRect(with:CGSize(width:width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [.font:font], context:nil).size.height + 30
        return height
    }

11.是否是手机号 判断逻辑 字符串是否是1开头的11位纯数字

    func isMobile() -> Bool {
        let mobileReg = "^1\d{10}$"
        let regextestmobile = NSPredicate(format: "SELF MATCHES %@",mobileReg)
        return regextestmobile.evaluate(with: self)
    }

12.字符串转 float 类型

     func toDouble() -> Float  {
        let real_value = NSDecimalNumber(string: "(self)").floatValue
        return real_value
      }

13.把汉字转化成拼音

   func transformToPinYin() -> String {
        let mutableString = NSMutableString(string: self)
        //把汉字转为拼音
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        //去掉拼音的音标
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        
        let string = String(mutableString)
        //去掉空格
        return string.replacingOccurrences(of: " ", with: "")
    }

14.日期date 转为 字符

  static func formatDate(_ date:Date,_ format:String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: date)
    }

15.字符串 转为 日期date

 static func dateWithFormat(string:String,format:String) -> Date? {
        let formatter = DateFormatter()
        formatter.locale = Locale.init(identifier: "zh_Cn")
        formatter.dateFormat = format
        let date = formatter.date(from: string)
        return date
    }

16.将字符串每隔数位分割符隔开

   /**
     * @param source 目标字符串
     * @param gap    相隔位数默认为3
     * @param gap    分割符,默认逗号
     * @return       用指定分隔符每隔指定位数隔开的字符串
    */
    func separateByCommas(source:String, gap:Int=3, seperator:Character = ",") -> String {
        var temp = source
        let count = temp.count
        let sepNum = count / gap
        guard sepNum >= 1 else {
            return temp
        }
       for i in 1...sepNum {
            let index = count - gap * i
            guard index != 0 else {
                break
            }
            temp.insert(seperator, at: temp.index(temp.startIndex, offsetBy: index))
        }
        return temp
    }

使用案例

     let str = "231233"
     let result =  str.separateByCommas(source: str)
     print(result) //打印结果:231,233

原文地址:https://blog.csdn.net/weixin_43259805/article/details/123293801

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_39470.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注