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

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

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

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


替换

把?替换为/

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

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

结果

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

过滤

过滤掉单个字符/

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

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

结果

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

过滤掉开头和结尾的空白

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

结果

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

切割

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

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

结果是一个数组

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

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

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

结果

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

拼接

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

结果

"1/2/3"@H_403_14@

猜你在找的Swift相关文章