Swift trim space/new line(字符串过滤空格和换行符)
2015-09-22 15:00
609 查看
Swift字符串过滤空格和换行符,写法与原来的objective-c有点不同,因为Swift中的字符串的索引不是int类型,而是Index类型。
转自: Swift trim space/new line
/// UIView's useful extensions. /// /// Author: huangyibiao /// Github: http://github.com/CoderJackyHuang/ /// Blog: http://www.hybblog.com/ extension String { /// Get the length of a string public func hyb_length() ->Int { return self.characters.count } /// 去掉字符串前后的空格,根据参数确定是否过滤换行符 /// /// - parameter trimNewline 是否过滤换行符,默认为false public func hyb_trim(trimNewline: Bool = false) ->String { if trimNewline { return self.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()) } return self.stringByTrimmingCharactersInSet(.whitespaceCharacterSet()) } /// 去掉字符串前面的空格,根据参数确定是否过滤换行符 /// /// - parameter trimNewline 是否过滤换行符,默认为false public func hyb_trimLeft(trimNewline: Bool = false) ->String { if self.isEmpty { return self } var index = self.startIndex while index != self.endIndex { let ch = self.characters[index] if ch == Character(" ") { index++ continue } else if ch == Character("\n") { if trimNewline { index++ continue } else { break } } break } return self.substringFromIndex(index) } /// 去掉字符串后面的空格,根据参数确定是否过滤换行符 /// /// - parameter trimNewline 是否过滤换行符,默认为false public func hyb_trimRight(trimNewline: Bool = false) ->String { if self.isEmpty { return self } var index = self.endIndex.predecessor() while index != self.startIndex { let ch = self.characters[index] if ch == Character(" ") { index-- continue } else if ch == Character("\n") { if trimNewline { index-- continue } else { index++ break } } break } return self.substringToIndex(index) } }
转自: Swift trim space/new line
相关文章推荐
- 自学Swift-斯坦福笔记整理(十三) Application Lifecycle and Core Motion
- Swift数组字典基本定义控制流基本应用
- 关东升的iOS实战系列图书 《iOS实战:入门与提高卷(Swift版)》已经上市
- 关东升的iOS实战系列图书 《iOS实战:入门与提高卷(Swift版)》已经上市
- Swift初探之纯代码写tabBar
- ios swift generator 文章推荐
- Swift版仿封装的个人界面,一分钟集成不是梦!
- Apple Swift编程语言入门教程
- Swift纯代码走进UICollectionView
- [book] iOS 8 Swift Programming Cookbook
- componentsSeparatedByString切割数组 swift
- Swift学习-运算符(二)
- Swift 第十课继承
- Swift学习-基础语法(一)
- ios swift 2 新的OptionSetType使用方法
- Swift 第九课 附属脚本
- Swift--从今天开始学习Swift
- Swift--面试题及答案
- Swift 2.0学习笔记(Day 15)——请注意数字类型之间的转换
- 《从零开始学Swift》学习笔记(Day 15)——请注意数字类型之间的转换