String是一系列char数据的集合,如”hello,world”或”albatross”。它是苹果公司针对Swift语言编写的管理字符串的对象。String以优雅的方式结合了Nsstring和NSMutableString的优点,并简化了接口的使用。本文介绍了关于String日常开发过程中的一系列方法,供大家查阅。
类型别名// MARK: 类型别名private func testTypeAliases() { let index = String.Index.self print("\(index)") let utf8index = String.UTF8Index.self print("\(utf8index)") let utf16index = String.UTF16Index.self print("\(utf16index)") let unicodeScalarIndex = String.UnicodeScalarIndex.self print("\(unicodeScalarIndex)") let greeting = "Guten Tag!" greeting[greeting.startIndex] // G greeting[greeting.endindex.predecessor()] // ! greeting[greeting.startIndex.successor()] // u greeting[greeting.startIndex.advancedBy(7)] // a}初始化
// MARK: 初始化private func testinitializers() { // 空字符串 var string:String = String() string = "" // char初始化 let char: Character = "阳" string = String(char) string = String.init(char) string = "\(char)" // 通过CharacterVIEw let charVIEw:String.CharacterVIEw = String.CharacterVIEw("阳君") string = String(charVIEw); // 通过UTF-16编码 let utf16:String.UTF16VIEw = string.utf16 string = String(utf16) // 通过UTF-8编码 string = String(string.utf8) // 多个字符串组合生成 string = String(stringInterpolation: "阳君","937447974") // char初始化,连续count次 string = String(count: 3,repeatedValue: char) // 通过其他常用数据初始化 string = String(stringInterpolationSegment: true) string = String(stringInterpolationSegment: 24) // 通过Nsstring初始化,不推荐 // 通过字符串生成字符串 string = Nsstring(string: "阳君") as String string = Nsstring.init(string: "阳君") as String // 组合生成 string = Nsstring(format: "%@","阳君") as String print("\(string)")}文件路径 *** 作
// MARK: - 文件路径 *** 作private func testWorkingWithPaths() { var path = "IOS/Swift" // 路径分割成数组 var pathComponents = (path as Nsstring).pathComponents // 数组组合成路径 path = Nsstring.pathWithComponents(pathComponents) // document目录 let documents:[String] = NSSearchPathForDirectorIEsInDomains(NSSearchPathDirectory.documentDirectory,NSSearchPathDomainMask.UserDomainMask,true) let docDirPath = documents.first! // 寻找文件夹下包含多少个路径 var complete = docDirPath.completePathIntoString(caseSensitive: true) // 寻找文件夹下包含指定扩展名的文件路径 var outname = "" let filterTypes = ["txt","pList"] complete = docDirPath.completePathIntoString(&outname,caseSensitive: true,matchesIntoArray: &pathComponents,filterTypes: filterTypes) print("completePathIntoString:\(complete)") // 添加路径 path = (docDirPath as Nsstring).stringByAppendingPathComponent("test") // 添加扩展 path = (path as Nsstring).stringByAppendingPathExtension("pList")! print("是否绝对路径:\((path as Nsstring).absolutePath)") print("最后一个路径名:\((path as Nsstring).lastPathComponent)") print("扩展名:\((path as Nsstring).pathExtension)") // 去掉扩展名 var tempPath:Any = (path as Nsstring).stringByDeletingPathExtension // 去掉最后一个路径 tempPath = (path as Nsstring).stringByDeletingLastPathComponent print("\(tempPath)") // 转%格式码 let allowedCharacters:NSCharacterSet = NSCharacterSet.controlCharacterSet() tempPath = path.stringByAddingPercentEnCodingWithAllowedCharacters(allowedCharacters) // 转可见 tempPath = path.stringByRemovingPercentEnCoding}文件读写 *** 作
// MARK: 文件读写 *** 作private func testfile() { var string = "阳君;937447974" // document目录 let documents:[String] = NSSearchPathForDirectorIEsInDomains(NSSearchPathDirectory.documentDirectory,true) let docDirPath = documents.first! let filePath = (docDirPath as Nsstring).stringByAppendingPathComponent("test.pList") let fileUrl = NSURL(fileURLWithPath: filePath) do { // 写入 try string.writetofile(filePath,atomically: true,enCoding: NSUTF8StringEnCoding) try string.writetoURL(fileUrl,enCoding: NSUTF8StringEnCoding) // 读取 // 自动解析 try string = String(contentsOffile: filePath) // 指定编码解析 try string = String(contentsOffile: filePath,enCoding: NSUTF8StringEnCoding) // 使用默认的编码解析,如果不能解析,采取默认解析并返回解析编码 var enCoding:nsstringencoding = NSUTF16littleEndianStringEnCoding try string = String(contentsOffile: filePath,usedEnCoding: &enCoding) // URl 读取 try string = String(contentsOfURL: fileUrl) try string = String(contentsOfURL: fileUrl,enCoding: NSUTF8StringEnCoding) try string = String(contentsOfURL: fileUrl,usedEnCoding: &enCoding) } catch { print("错误:\(error)") }}获取字符串的Swift属性
// MARK: - 获取字符串的Swift属性private func testGettingPropertIEs() { let string = String(stringInterpolation: "阳君","y;j","937447974") // String.CharacterVIEw print("String.CharacterVIEw:\(string.characters)") // String.UnicodeScalarVIEw print("String.UnicodeScalarVIEw:\(string.unicodeScalars)") // String.UTF16VIEw print("String.UTF16VIEw:\(string.utf16)") // String.UTF8VIEw print("String.UTF8VIEw:\(string.utf8)") // hash值 print("hashValue:\(string.hashValue)") // 是否为空 print("isEmpty:\(string.isEmpty)")}获取字符串长度
// MARK: 获取字符串长度private func testGettingLength() { let string = "阳君;937447974" // 起始位置 var index = string.startIndex // 结束位置 index = string.endindex print("\(index)") // Nsstring方式获取长度 var length = (string as Nsstring).length print("\(length)") // 通过编码获取长度 length = string.lengthOfBytesUsingEnCoding(NSUTF8StringEnCoding) // 返回存储时需要指定的长度 length = string.maximumLengthOfBytesUsingEnCoding(NSUTF8StringEnCoding)}大小写变化
// MARK: - 大小写变化private func testChangingCase() { let str = "阳君;y937447974J" // 大写和小写 print("uppercaseString:\(str.uppercaseString);lowercaseString:\(str.lowercaseString)")}得到数值
// MARK: 得到数值private func testGettingNumericValues() { let string = "24" let nStr = string as Nsstring // 借用Nsstring输出 print("doubleValue:\(nStr.doubleValue)") print("floatValue:\(nStr.floatValue)") print("intValue:\(nStr.intValue)") print("integerValue:\(nStr.integerValue)") print("longLongValue:\(nStr.longLongValue)") print("boolValue:\(nStr.boolValue)")}增加字符串
// MARK: - 增加字符串private func testCombiningStrings() { var str = "阳君;937447974" // 添加字符串 str.appendContentsOf(";Swift") str += ";11" str.write("222") // string后增加字符串并生成一个新的字符串 str = str.stringByAppendingString(str) // string后增加组合字符串并生成一个新的字符串 str = str.stringByAppendingFormat(";%@","OC") // string后增加循环字符串,stringBypaddingTolength:完毕后截取的长度;startingAtIndex:从增加的字符串第几位开始循环增加。 str = str.stringBypaddingTolength(30,withString:";Swift",startingAtIndex:3) // 指定位置插入Character str.insert("5",atIndex: str.endindex.advancedBy(-1)) // 指定位置插入字符串 str.insertContentsOf("78".characters,at: str.startIndex.advancedBy(9))}分割字符串
// MARK: 分割字符串private func testdivIDingStrings() { let str = "阳君;937447974" // 根据指定的字符串分割成数组 var array = str.componentsSeparatedByString(";") // 通过系统自带的分割方式分割字符串 array = str.componentsSeparatedByCharactersInSet(NSCharacterSet.lowercaseLetterCharacterSet()) print("array\(array)") // 指定位置后的字符串 var tempStr = str.substringFromIndex(str.startIndex.advancedBy(3)) // 指定位置前的字符串 tempStr = str.substringToIndex(str.startIndex.advancedBy(3)) // 指定范围的字符串 let range = str.endindex.advancedBy(-6)..<str.endindex tempStr = str.substringWithRange(range) print("tempStr:\(tempStr)")}查找字符串
// MARK: 查找字符串private func testFindingStrings() { let str = "阳君;\n937447974"; let searchRange = str.startIndex ..< str.startIndex.advancedBy(10) // 根据NSCharacterSet查找 let cSet = NSCharacterSet.uppercaseLetterCharacterSet() var range = str.rangeOfCharacterFromSet(cSet) // 根据字符串查找 range = str.rangeOfString("93") range = str.rangeOfString("93",options: NsstringCompareOptions.CaseInsensitiveSearch,range: searchRange,locale: nil) print("\(range)") // block 行查找 str.enumeratelines { (line,stop) -> () in print("\(line)") if "93" == line { stop = true } } // block查找,可设置查找方式,并得到找到的位置 str.enumerateSubstringsInRange(searchRange,options: NsstringEnumerationoptions.ByComposedCharacterSequences) { (substring,substringRange,enclosingRange,stop) -> () in print("\(substring)") if "9" == substring { print("\(substringRange)") stop = true } }}替换字符串
// MARK: 替换字符串private func testReplacingSubstrings() { var string = "阳君;937447974" let replacingRange = string.startIndex ... string.startIndex.advancedBy(3) // 全局替换 string = string.stringByReplacingOccurrencesOfString(";",withString: "+") // 设置替换的模式,并设置范围 string = string.stringByReplacingOccurrencesOfString("+",withString: ";",options: NsstringCompareOptions.CaseInsensitiveSearch,range: replacingRange) //将指定范围的字符串替换为指定的字符串 string.replaceRange(replacingRange,with: "12345") string = string.stringByReplacingCharactersInRange(replacingRange,withString: "12345")}删除字符串
// MARK: 删除字符串private func testRemovingSubstrings() { var string = "阳君;937447974" // 删除指定位置的字符串 string.removeAtIndex(string.startIndex.advancedBy(1)) // 根据范围删除字符串 let range = string.endindex.advancedBy(-6)..<string.endindex string.removeRange(range) // 删除所有 string.removeAll() string.removeAll(keepCapacity: true)}比较字符串
// MARK: 比较字符串private func testComparingStrings() { var string = "阳君;937447974" let compareStr = "阳君;837447974" let searchRange = string.startIndex ..< string.endindex // 前缀 var isHas = string.hasPrefix("阳君") print("hasPrefix:\(isHas)") // 后缀 isHas = string.hasSuffix("Swift") print("hasSuffix:\(isHas)") // 全比较是否相同 isHas = string == compareStr // 比较大小 var result = string.compare(compareStr) // 添加比较范围 result = string.compare(compareStr,range: searchRange,locale: nil) print("result:\(result)") // 返回两个字符串相同的前缀 string = string.commonPrefixWithString(compareStr,options: NsstringCompareOptions.CaseInsensitiveSearch)}其他 参考资料
NSString Class Reference
NSMutableString Class Reference
The Swift Programming Language (Swift 2.1)
String Structure Reference
时间 | 描述 |
---|---|
2015-10-21 | 根据Swift2.1 String的API总结 |
版权所有:http://blog.csdn.net/y550918116j
总结以上是内存溢出为你收集整理的String Programming Guide全部内容,希望文章能够帮你解决String Programming Guide所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)