1.String截取的相关操作.
/// 截取第一个到第任意位置
///
/// - Parameter end: 结束的位值
/// - Returns: 截取后的字符串
func stringCut(end: Int) -> String{
if !(end <= count) { return self }
let sInde = index(startIndex, offsetBy: end)
return String(self[..<sInde])
}
/// 截取人任意位置到结束
///
/// - Parameter end:
/// - Returns: 截取后的字符串
func stringCutToEnd(star: Int) -> String {
if !(star < count) { return "截取超出范围" }
let sRang = index(startIndex, offsetBy: star)..<endIndex
return String(self[sRang])
}
/// 截取最后几位
///
/// - Parameter last:
/// - Returns: 截取后的字符串
func stringCutLastEnd(last: Int) -> String {
if !(last < count) { return "截取超出范围" }
let sRang = index(endIndex, offsetBy: -last)..<endIndex
return String(self[sRang])
}
/// 字符串截取 3 6
/// e.g let aaa = "abcdefghijklmnopqrstuvwxyz" -> "cdef"
/// - Parameters:
/// - start: 开始位置 3
/// - end: 结束位置 6
/// - Returns: 截取后的字符串 "cdef"
func startToEnd(start: Int,end: Int) -> String {
if !(end < count) || start > end { return "取值范围错误" }
var tempStr: String = ""
for i in start...end {
let temp: String = self[self.index(self.startIndex, offsetBy: i - 1)].description
tempStr += temp
}
return tempStr
}
2.字符串插入.
///
/// - Parameters:
/// - content: 插入内容
/// - locat: 插入的位置
/// - Returns: 添加后的字符串
func stringInsert(content: String,locat: Int) -> String {
if !(locat < count) { return "截取超出范围" }
let str1 = stringCut(end: locat)
let str2 = stringCutToEnd(star: locat)
return str1 + content + str2
}
3.计算字符串尺寸.
/// 计算字符串的尺寸
///
/// - Parameters:
/// - text: 字符串
/// - rectSize: 容器的尺寸
/// - fontSize: 字体
/// - Returns: 尺寸
///
func getStringSize(rectSize: CGSize,fontSize: CGFloat) -> CGSize {
let str: NSString = self as NSString
let rect = str.boundingRect(with: rectSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: fontSize)], context: nil)
return CGSize(width: ceil(rect.width), height: ceil(rect.height))
}
func getStringSize(fontSize:CGFloat) -> CGSize{
return self.getStringSize(rectSize: CGSize(width: CGFloat(MAXFLOAT), height: CGFloat(MAXFLOAT)), fontSize: fontSize)
}
4.根据字符串拆分数组.
/// 输入字符串 输出数组
/// e.g "qwert" -> ["q","w","e","r","t"]
/// - Returns: ["q","w","e","r","t"]
func stringToArr() -> [String] {
let num = count
if !(num > 0) { return [""] }
var arr: [String] = []
for i in 0..<num {
let tempStr: String = self[self.index(self.startIndex, offsetBy: i)].description
arr.append(tempStr)
}
return arr
}
5.将字符串中中文encoding.
/// 字符URL格式化,中文路径encoding
///
/// - Returns: 格式化的 url
func stringEncoding() -> String {
let url = self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
return url!
}
6.判断字符串中是否包含XXX.
///是否包含字符串
func containsIgnoringCase(find: String) -> Bool{
return self.range(of: find, options: .caseInsensitive) != nil
}
///判断String是否存在汉字
func isIncludeChineseIn() -> Bool {
for (_, value) in self.enumerated() {
if ("\u{4E00}" <= value && value <= "\u{9FA5}") {
return true
}
}
return false
}
7.去除字符串中的XXX.
///去除String中空格
func trim() -> String {
return self.replacingOccurrences(of: " ", with: "").trimmingCharacters(in: CharacterSet.whitespaces)
}
/// 删除字符串中Unicode.Cc/Cf字符,类似于\0这种
func stringByRemovingControlCharacters() -> String {
let controlChars = CharacterSet.controlCharacters
var range = self.rangeOfCharacter(from: controlChars)
var mutable = self
while let removeRange = range {
mutable.removeSubrange(removeRange)
range = mutable.rangeOfCharacter(from: controlChars)
}
return mutable
}
8.修改字符串中数字的样式.
/// 修改字符串中数字样式,将其加粗,变黑,加大4个字号,同时修改行间距
///
/// - Parameters:
/// - fontsize: 非数字字号
/// - color: 非数字颜色
/// - lineSpace: 行间距
/// - Returns: 修改完成的AttributedString
func attributeNumber(BoldFontSize fontsize:CGFloat, color:UIColor,lineSpace:CGFloat?)->NSMutableAttributedString{
let AttributedStr = NSMutableAttributedString(string: self, attributes: [.font: UIFont.systemFont(ofSize: fontsize), .foregroundColor: color])
for i in 0 ..< self.count {
let char = self.utf8[self.index(self.startIndex, offsetBy: i)]
if (char > 47 && char < 58) {
AttributedStr.addAttribute(.foregroundColor, value: UIColor(red: 33 / 255.0, green: 34 / 255.0, blue: 35 / 255.0, alpha: 1), range: NSRange(location: i, length: 1))
AttributedStr.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: fontsize + 4), range: NSRange(location: i, length: 1))
}
}
if let space = lineSpace {
let paragraphStyleT = NSMutableParagraphStyle()
paragraphStyleT.lineSpacing = space
AttributedStr.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyleT, range: NSMakeRange(0,self.count))
}
return AttributedStr
}
/// 给字符串中数字变样式
///
/// - Parameters:
/// - fontsize: 字体大小
/// - color: 非数字颜色
/// - hcolor: 数字颜色
/// - B: 是否加粗变大
/// - Returns: 修改完成字符串
func attributeNumber(_ fontsize :CGFloat,color:UIColor,hcolor:UIColor,B:Bool)-> NSMutableAttributedString{
let AttributedStr = NSMutableAttributedString(string: self, attributes: [.font: UIFont.systemFont(ofSize: fontsize), .foregroundColor: color])
for i in 0 ..< self.count {
let char = self.utf8[self.index(self.startIndex, offsetBy: i)]
if (char > 47 && char < 58) {
AttributedStr.addAttribute(.foregroundColor, value: hcolor, range: NSRange(location: i, length: 1))
if B {
AttributedStr.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: fontsize + 2), range: NSRange(location: i, length: 1))
}
}
}
return AttributedStr
}
9.将字符串修改为URL.
public protocol URLConvertibleProtocol {
var URLValue: URL? { get }
var URLStringValue: String { get }
}
extension String: URLConvertibleProtocol {
///String转换成URL
public var URLValue: URL? {
if let URL = URL(string: self) {
return URL
}
let set = CharacterSet()
.union(.urlHostAllowed)
.union(.urlPathAllowed)
.union(.urlQueryAllowed)
.union(.urlFragmentAllowed)
return self.addingPercentEncoding(withAllowedCharacters: set).flatMap { URL(string: $0) }
}
public var URLStringValue: String {
return self
}
}
10.将字符串拼接到目录后.
extension String{
/**
将当前字符串拼接到cache目录后面
*/
func cacheDir() -> String{
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
return (path as NSString).appendingPathComponent((self as NSString).lastPathComponent)
}
/**
将当前字符串拼接到doc目录后面
*/
func docDir() -> String{
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
return (path as NSString).appendingPathComponent((self as NSString).lastPathComponent)
}
/**
将当前字符串拼接到tmp目录后面
*/
func tmpDir() -> String{
let path = NSTemporaryDirectory() as NSString
return path.appendingPathComponent((self as NSString).lastPathComponent)
}
}
10.给String添加各种类型转换.
extension String {
var length: Int {
///更改成其他的影响含有emoji协议的签名
return self.utf16.count
}
var doubleValue: Double {
return (self as NSString).doubleValue
}
var intValue: Int32 {
return (self as NSString).intValue
}
var floatValue: Float {
return (self as NSString).floatValue
}
var integerValue: Int {
return (self as NSString).integerValue
}
var longLongValue: Int64 {
return (self as NSString).longLongValue
}
var boolValue: Bool {
return (self as NSString).boolValue
}
}
String是我们开发中最常用类之一,所以我们可能需要对其进行很多操作.
使用Extension为其添加我们需要的功能与属性,是一种较为完善的方式,使用起来很轻便,一目了然,对代码的重用性,解耦性都有很大的帮助.
所以我们应该更习惯的以Extension的方式来拓展我们所需要的类.
这里我把我常用的方法罗列出来,也欢迎各位分享出你们所常用的String拓展.
如果需要使用我集成的方法,可以从github上下载,直接把String+Extension.swift拖入项目即可.
demo地址:String-Extension.求star.
有问题欢迎探讨.