Jelajahi Sumber

string 扩展

harry 1 tahun lalu
induk
melakukan
a5f2dcbeab
1 mengubah file dengan 49 tambahan dan 0 penghapusan
  1. 49 0
      BFCommonKit/Classes/BFCategorys/BFString+Ext.swift

+ 49 - 0
BFCommonKit/Classes/BFCategorys/BFString+Ext.swift

@@ -222,6 +222,55 @@ public extension String{
         let msg = NSLocalizedString(self, tableName: nil, bundle: resourceBundle!, value: noFindStr, comment: "")
         return msg
     }
+    func BinaryToDecimal() -> Int {
+        var sum : Int = 0
+        for c in self {
+            if let number = Int(String(c)) {
+                sum = sum*2 + number
+            }
+        }
+        return sum
+    }
+    
+    // 十六进制转十进制
+    func HexToDecimal() -> Int {
+        var sum: Int = 0
+        let str:String = self.uppercased()
+        for c in str.utf8 {
+            sum = sum*16 + Int(c) - 48
+            if c > 64 {
+                sum -= 7
+            }
+        }
+        return sum
+    }
+    
+    // 定位+长度方式 截取字符串
+    func bf_substring_len(location: Int, len: Int) -> String{
+        if location >= self.count {
+            return ""
+        }
+        if location + len >= self.count {
+            return self.substring(from: location)
+        }
+        let start = self.index(self.startIndex, offsetBy: Int(location))
+        let end = self.index(self.startIndex, offsetBy: Int(location + len - 1))
+        return String(self[start...end])
+    }
+    
+    // 下标方式截取字符串
+    func bf_substring_end(begin: Int, end: Int) -> String{
+        if begin >= self.count {
+            return ""
+        }
+        if end >= self.count {
+            return self.substring(from: begin)
+        }
+        let range = self.index(self.startIndex, offsetBy: Int(begin))...self.index(self.startIndex, offsetBy: Int(end))
+
+        return String(self[range])
+    }
 }
 
  
+