★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:MindDraft
➤博主域名:https://www.zengqiang.org
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9879997.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
NS是Cocoa类对象类型的前缀,来源于乔布斯建立的另一家公司--NeXT
NSString的使用方法,和Swift语言中的String有很多相似之处。
1、字符串的定义
String类
var str1:String = "My name is strengthen"
NSString类
1 var nsStr1:NSString = "My name is strengthen" 2 var nsStr2:NSString = NSString(string: "My name is strengthen") 3 var nsStr3:NSString = NSString(string: str1)
String类空字符串
1 var strEmpty1:String = "" 2 var strEmpty2:String = String() 3 dump(strEmpty2) 4 //Print - "" 5 //判断是否为空 6 //方式1 7 print(strEmpty2.isEmpty) 8 //Print true 9 10 //方式2 11 print(strEmpty2.count == 0) 12 //Print true 13 14 //方式3 已初始化,不为nil 15 print(strEmpty2 == nil) 16 //Print false 17 18 //方式4 19 print(strEmpty2 is NSNull ) 20 //Print false
NSString类空字符串
1 var nsStrEmpty1:NSString = NSString(string: "") 2 var nsStrEmpty2:NSString = NSString(string: String()) 3 4 //方式1 区分大小写比较,用来判断是否为空 5 let check = nsStrEmpty2.caseInsensitiveCompare("") == .orderedSame 6 print(check) 7 //Print true 8 9 //方式2 已初始化,不为NSNull 10 print(nsStrEmpty2 is NSNull ) 11 //Print false
String 转换为 NSString,转换需要遵循严格的类型转化。
var nsStr4: NSString = str1 as NSString
NSString 转换为String,转换需要遵循严格的类型转化。
var str2:String = nsStr2 as String
2、字符串格式化
格式说明由“%”和格式字符组成,如%d%f等。它的作用是将输出的数据转换为指定的格式输出。
%d 整型输出,%ld长整型输出;
%o 以八进制数形式输出整数;
%x 以十六进制数形式输出整数,或输出字符串的地址;
%u 以十进制数输出unsigned型数据(无符号数)。
注意:%d与%u有无符号的数值范围,也就是极限的值,否则打印错误数值。
%c 用来输出一个字符;
%s 用来输出一个字符串;
%f 用来输出实数,以小数形式输出,默认情况下保留小数点6位;
%.10f 用来输出实数,保留小数点10位;
%e 以指数形式输出实数;
%g 根据大小自动选f格式或e格式,且不输出无意义的零。
格式化:
1 let nsStr = NSString(format: "%f", 66.666) 2 let str =String(format: "%f", 66.666)
拼接:
1 var str1 = NSString(string: "hello") 2 var str2 = str1.appending("strengthen") 3 var str3 = str1 + "strengthen"
格式化拼接:
1 let x:Int = 1 2 let y:Double = 0.56 3 let sum:Double = Double(x) + y 4 print(String(format: "%d + %.2f = \(sum)", x, y)) 5 //Print 1 + 0.56 = 1.56
3、字符定义
Character转ASCII整数值:
1 //Character扩展方法 2 extension Character 3 { 4 //转ASCII整数值(定义小写为整数值) 5 var ascii: Int { 6 get { 7 return Int(self.unicodeScalars.first!.value) 8 } 9 } 10 }
ASCII整数值转Character:
1 //Int扩展方法 2 extension Int 3 { 4 //属性:ASCII值(定义大写为字符值) 5 var ASCII:Character 6 { 7 get {return Character(UnicodeScalar(self)!)} 8 } 9 }
CharacterSet 各个枚举类型的含义:
.controlCharacters:控制符
.whitespaces:空格
.newlines:换行符
.whitespacesAndNewlines:空格换行
.decimalDigits:小数
.letters:文字
.lowercaseLetters:小写字母
.uppercaseLetters:大写字母
.nonBaseCharacters:非基础
.alphanumerics:字母数字
.decomposables:可分解
.illegalCharacters:非法
.punctuationCharacters:标点
.capitalizedLetters:大写
.symbols:符号
4、字符串拼接
1 var str1 = "My name is " 2 var str2 = "strengthen" 3 4 //方式1 5 var strConnect1 = str1 + str2 6 7 //方式2 8 var strConnect2 = "\(str1)\(str2)" 9 10 //方式3 11 var str3:NSString = NSString(string: "My name is ") 12 var strConnect3 = str3.appending("strengthen") 13 14 //方式4 字符数组转字符串 15 let arrayStr = ["s","t","r","e","n","g","t","h","e","n","!"] 16 //方式4.1 17 let str1 = arrayStr.joined(separator: "") 18 let str2 = arrayStr.joined(separator: "-") 19 print("\(str1) ", terminator: "") 20 print("\(str2) ", terminator: "") 21 //strengthen! 22 //s-t-r-e-n-g-t-h-e-n-! 23 24 //方式4.2:注意与方式4.1比较,方式4.2只在首位添加"-" 25 let str3 = arrayStr.reduce("", {$0 + $1}) 26 let str4 = arrayStr.reduce("-", {$0 + $1}) 27 print("\(str3) ", terminator: "") 28 print("\(str4) ", terminator: "") 29 //strengthen! 30 //-strengthen! 31 32 //方式5:整数数组转字符串 33 let arrayInt = [0,1,2,3,4,5,6,7,8,9] 34 let dataInt = arrayInt.map(String.init) 35 let strInt = dataInt.joined(separator: "-") 36 print("\(strInt) ", terminator: "") 37 //0-1-2-3-4-5-6-7-8-9
5、获取字符串中指定索引处的字符
每个String值都有一个关联的索引类型,String.Index它对应Character于字符串中每个值的位置。
不同的字符可能需要不同的内存量来存储,因此为了确定哪个Character位于特定位置,您必须从开头或结尾迭代每个Unicode标量String。
因此,Swift字符串不能用整数值索引。可以使用index(before:)和index(after:)方法访问给定索引之前和之后的索引String。
要访问远离给定索引的索引,可以使用该index(_:offsetBy:)方法而不是多次调用其中一种方法。
1 let str = "Strengthen" 2 3 print(str[str.startIndex]) 4 //Print S 5 print(str[str.index(before: str.endIndex)]) 6 //Print n 7 8 let index = str.index(str.startIndex, offsetBy: 0) 9 print(str[index]) 10 //Print S 11 12 //endIndex属性是a中最后一个字符后的位置String。 13 //因此endIndex属性不是字符串下标的有效参数。 14 str[str.endIndex] 15 // Error 16 17 str[str.index(after: str.endIndex)] 18 // Error
扩展String类
1 //String扩展 2 extension String { 3 //subscript函数可以检索数组中的值 4 //直接按照索引方式截取指定索引的字符 5 subscript (_ i: Int) -> Character { 6 //读取字符 7 get {return self[index(startIndex, offsetBy: i)]} 8 9 //修改字符 10 set 11 { 12 if newValue is Character 13 { 14 //转换为字符数组 15 var arr:[Character] = Array(self) 16 arr[i] = newValue 17 self = String(arr) 18 } 19 } 20 } 21 }
6、字符串插入
var str = "Strengthen"
若要将单个字符插入到指定索引处的字符串中,请使用该insert(_:at:)方法
1 str.insert("!", at: str.endIndex) 2 print(str) 3 //Print Strengthen!
指定索引处插入另一个字符串的内容,请使用该insert(contentsOf:at:)方法。
1 str.insert(contentsOf: " hello", at: str.index(before: str.endIndex)) 2 print(str) 3 //Print Strengthe hellon
7、字符串删除
var str = "Strengthen"
要从指定索引处的字符串中删除单个字符,请使用remove(at:)方法
1 str.remove(at: str.index(before: str.endIndex)) 2 print(str) 3 //Print Strengthe
删除指定范围内的子字符串,请使用removeSubrange(_:)方法
注意下方代码从后往前用负数的方式
1 let range = str.index(str.endIndex, offsetBy: -5)..<str.endIndex 2 str.removeSubrange(range) 3 print(str) 4 //Print Stren
注意(总结6、字符串插入和7、字符串删除):
使用insert(_:at:),insert(contentsOf:at:),remove(at:),和removeSubrange(_:),对符合任何类型的方法RangeReplaceableCollection的协议。
这包括String以及集合类型,如Array,Dictionary和Set。
8、获取字符串长度
1 var str = "Strengthen" 2 print(str.count) 3 //Print 10
9、字符串比较
Swift提供了三种比较文本值的方法:字符串和字符相等,前缀相等和后缀相等。
注意:Swift中的字符串和字符比较不是区域设置敏感的。
1 let str1="hello," 2 let str2="strengthen" 3 let str3="hello,strengthen" 4 5 let compare1 = str1==str2 6 //false 7 8 let compare2 = str1+str2 == str3 9 //true 10 11 let compare3 = str1 < str2 12 //true 13 14 let compare4 = str1 != str2 15 //true
字符串比较的方法:isEqual
1 let str = "Hello World!" 2 print(str.isEqual("Hello World!")) 3 //true
10、检查字字符串前缀
检查字符串是否具有特定的字符串前缀调用字符串hasPrefix(_:),其采用类型的单个参数String并返回布尔值
1 let romeoAndJuliet = [ 2 "Act 1 Scene 1: Verona, A public place", 3 "Act 1 Scene 2: Capulet\'s mansion", 4 "Act 1 Scene 3: A room in Capulet\'s mansion", 5 "Act 1 Scene 4: A street outside Capulet\'s mansion", 6 "Act 1 Scene 5: The Great Hall in Capulet\'s mansion", 7 "Act 2 Scene 1: Outside Capulet\'s mansion", 8 "Act 2 Scene 2: Capulet\'s orchard", 9 "Act 2 Scene 3: Outside Friar Lawrence\'s cell", 10 "Act 2 Scene 4: A street in Verona", 11 "Act 2 Scene 5: Capulet\'s mansion", 12 "Act 2 Scene 6: Friar Lawrence\'s cell" 13 ]
hasPrefix(_:)方法与romeoAndJuliet数组一起使用来计算播放的第1幕中的场景数量:
1 var act1SceneCount = 0 2 for scene in romeoAndJuliet { 3 if scene.hasPrefix("Act 1 ") { 4 act1SceneCount += 1 5 } 6 } 7 print("There are \(act1SceneCount) scenes in Act 1") 8 // Prints "There are 5 scenes in Act 1"
11、检查字符串后缀
检查字符串是否具有特定的字符串后缀调用字符串hasSuffix(_:),其用类型的单个参数String并返回布尔值
1 let romeoAndJuliet = [ 2 "Act 1 Scene 1: Verona, A public place", 3 "Act 1 Scene 2: Capulet\'s mansion", 4 "Act 1 Scene 3: A room in Capulet\'s mansion", 5 "Act 1 Scene 4: A street outside Capulet\'s mansion", 6 "Act 1 Scene 5: The Great Hall in Capulet\'s mansion", 7 "Act 2 Scene 1: Outside Capulet\'s mansion", 8 "Act 2 Scene 2: Capulet\'s orchard", 9 "Act 2 Scene 3: Outside Friar Lawrence\'s cell", 10 "Act 2 Scene 4: A street in Verona", 11 "Act 2 Scene 5: Capulet\'s mansion", 12 "Act 2 Scene 6: Friar Lawrence\'s cell" 13 ]
使用该hasSuffix(_:)方法计算在Capulet的mansion和Friar Lawrence的单元格内或周围发生的场景数量:
1 var mansionCount = 0 2 var cellCount = 0 3 for scene in romeoAndJuliet { 4 if scene.hasSuffix("Capulet\'s mansion") { 5 mansionCount += 1 6 } else if scene.hasSuffix("Friar Lawrence\'s cell") { 7 cellCount += 1 8 } 9 } 10 print("\(mansionCount) mansion scenes; \(cellCount) cell scenes") 11 // Prints "6 mansion scenes; 2 cell scenes"
12、字符串包含
1 let str = "strengthen"; 2 let exist1 = (str as NSString).contains("stren") 3 let exist2 = str.contains("stren") 4 print(exist1) 5 print(exist2) 6 //Print true
13、查找字符
1 let str = "strengthen" 2 print(str.index(of: "r")?.encodedOffset) 3 //Print Optional(2) 4 print(str.index(of: "z")?.encodedOffset) 5 //Print nil
14、截取字符串
字符串和子字符串之间的区别在于,作为性能优化,子字符串可以重用用于存储原始字符串的部分内存,或者用于存储另一个子字符串的内存的一部分。
1 let greeting = "Hello, world!" 2 let index = greeting.firstIndex(of: ",") ?? greeting.endIndex 3 let beginning = greeting[..<index] 4 // beginning is "Hello" 5 6 // Convert the result to a String for long-term storage. 7 let newString = String(beginning)
15、Trim字符串:trimmingCharacters
(1)、删除前后多余的空格
1 //原始字符串 2 let str1 = " strengthen " 3 //除去前后空格 4 let str2 = str1.trimmingCharacters(in: .whitespaces) 5 print(str2) 6 //Print strengthen
(2)、删除前后指定的字符
1 //原始字符串 2 let str3 = "((strengthen))" 3 //删除前后() 4 let characterSet = CharacterSet(charactersIn: "()") 5 let str4 = str1.trimmingCharacters(in: characterSet) 6 print(str4) 7 //Print strengthen
16、字符串分割
1 let str = "s、t、r、e、n、g、t、h、e、n" 2 //方法1:使用components(separatedBy:" ")方法 3 //字符串转数组 4 let array1 = str.components(separatedBy:"、") 5 print("\(array1) ", terminator: "") 6 //Print ["s", "t", "r", "e", "n", "g", "t", "h", "e", "n"] 7 8 //方法2:使用characters.split()方法 9 let str = "s、t、r、e、n、g、t、h、e、n" 10 print("原始字符串:\(str)") 11 //Print 原始字符串:s、t、r、e、n、g、t、h、e、n 12 let splitedArray = str.characters.split{$0 == "、"}.map(String.init) 13 print("拆分后的数组:\(splitedArray)") 14 //Print 拆分后的数组:["s", "t", "r", "e", "n", "g", "t", "h", "e", "n"]
字符串转字符数组:
1 let str = "I am Strengthen" 2 let array2 = str.components(separatedBy:" ") 3 print("\(array2) ", terminator: "") 4 //["I", "am", "Strengthen"]
字符数组转字符串:
1 let arrayStr = ["s","t","r","e","n","g","t","h","e","n","!"] 2 3 //方式1 4 let str1 = arrayStr.joined(separator: "") 5 let str2 = arrayStr.joined(separator: "-") 6 print("\(str1) ", terminator: "") 7 print("\(str2) ", terminator: "") 8 //strengthen! 9 //s-t-r-e-n-g-t-h-e-n-! 10 11 //方式2:注意与方式1比较,方式2只在首位添加"-" 12 let str3 = arrayStr.reduce("", {$0 + $1}) 1
请发表评论