swift中想要把字符串分割为字符数组
搜:
swift split string to char array
参考:
最后写成:
1 2 3 4 5 6 7 8 9 | //split string into character array func splitSingleStrToCharArr(strToSplit:String) -> [Character] { print( "strToSplit=\(strToSplit)" ) //strToSplit=周杰伦 let splitedCharArr:[Character] = Array(strToSplit.characters) print( "splitedCharArr=\(splitedCharArr)" ) //splitedCharArr=["周", "杰", "伦"] return splitedCharArr } |
即可。
用法:
1 2 3 4 5 6 | /* * splitSingleStrToCharArr demo */ let stringToSplit:String = "一个字符串" let spiltedCharArr:[Character] = splitSingleStrToCharArr(stringToSplit) print( "spiltedCharArr=\(spiltedCharArr)" ) //["一", "个", "字", "符", "串"] |
[后记]
后来又演化为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | extension String { //split string into character array //周杰伦 -> ["周", "杰", "伦"] func splitToCharArr() -> [Character] { let splitedCharArr:[Character] = Array(self.characters) return splitedCharArr } //split string into string array, normally seperator is white space //if origin string not containing white space, then pass the empty string here, will split to every single char as string func splitToStrArr(seperatorStr:String = "" ) -> [String] { guard self.notEmpty else { return [String]() } //print("strToSplit=\(strToSplit), seperatorStr=\(seperatorStr)") var splitedStrArr:[String] = [String]() if seperatorStr.notEmpty { let seperatorChar:Character = seperatorStr.splitToCharArr()[0] splitedStrArr = self.characters.split(seperatorChar).map(String.init) } else { //split string(without space) into every single char as string let splitedCharArr:[Character] = self.splitToCharArr() for eachChar in splitedCharArr { splitedStrArr.append(String(eachChar)) } } //print("splitedStrArr=\(splitedStrArr)") return splitedStrArr } } |
示例用法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /* * splitToCharArr demo */ let stringToSplit:String = "一个字符串" let spiltedCharArr:[Character] = stringToSplitsplitToCharArr.() print( "spiltedCharArr=\(spiltedCharArr)" ) //["一", "个", "字", "符", "串"] /* * splitToStrArr demo */ //let noneSeperatorStr:String = "" let strWithoutSpace:String = "中间没有空格单个字符串" //let splitedStrArr_withoutSpace:[String] = strWithoutSpace.splitToStrArr(noneSeperatorStr) let splitedStrArr_withoutSpace:[String] = strWithoutSpace.splitToStrArr() print( "splitedStrArr_withoutSpace=\(splitedStrArr_withoutSpace)" ) //["中", "间", "没", "有", "空", "格", "单", "个", "字", "符", "串"] let spaceSeperatorStr:String = " " let stringContainingSpace:String = "中 间 有 空 格 的 字 符 串 " let splitedStrArr_containingSpace:[String] = stringContainingSpace.splitToStrArr(spaceSeperatorStr) print( "splitedStrArr_containingSpace=\(splitedStrArr_containingSpace)" ) //["中", "间", "有", "空", "格", "的", "字", "符", "串"] |
注:更多其他函数,已整理至我的:
https://github.com/crifan/CrifanString
转载请注明:在路上 » [已解决]swift把字符串分割为字符数组