Swift 字符串替换/过滤/切割/拼接

前端之家收集整理的这篇文章主要介绍了Swift 字符串替换/过滤/切割/拼接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

原创blog,转载请注明出处
blog.csdn.net/hello_hwc

之前写过一篇Swift String的基础,想了解的同学可以看下。
http://www.jb51.cc/article/p-kvgdhjox-zs.html


替换

把?替换为/

var url = "http://blog.csdn.net/hello_hwc?viewmode=list"

var filtered = url.stringByReplacingOccurrencesOfString("?",withString: "/",options: NSStringCompareOptions.LiteralSearch,range: nil)

结果

"http://blog.csdn.net/hello_hwc/viewmode=list"

过滤

过滤掉单个字符/

var url = "http://blog.csdn.net/hello_hwc?viewmode=list"

var filtered = url.stringByReplacingOccurrencesOfString("/",withString: "",range: nil)

结果

"http:blog.csdn.nethello_hwc?viewmode=list"

过滤掉开头和结尾的空白

var url = " http://blog.csdn.net/hello_hwc?viewmode=list "
var newString = url.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

结果

"http://blog.csdn.net/hello_hwc?viewmode=list"

切割

对字符串使用/作为分隔符来切割,不允许空字符串
使用split函数

var url = "http://blog.csdn.net/hello_hwc?viewmode=list"
let splitedarray = split(url){$0 == "/"}

结果是一个数组

"http:"
"blog.csdn.net"
"hello_hwc?viewmode=list"

对字符串使用/作为分隔符来切割,允许空字符串

var url = "http://blog.csdn.net/hello_hwc?viewmode=list"
let arrayresult = split(url,maxSplit:url.lengthOfBytesUsingEncoding(NSUTF8StringEncoding),allowEmptySlices: true) { (char:Character) -> Bool in
    return char == "/"
}

结果

"http:"
""
"blog.csdn.net"
"hello_hwc?viewmode=list"

拼接

let splitedarray = ["1","2","3"]
let result = join("/",splitedarray)

结果

"1/2/3"

猜你在找的Swift相关文章