[Swift]字符串(String類、NSString類)經常使用操做

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/ 
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-xdzplqdj-hu.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

NS是Cocoa類對象類型的前綴,來源於喬布斯創建的另外一家公司--NeXT
NSString的使用方法,和Swift語言中的String有不少類似之處。git

一、字符串的定義
String類github

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類空字符串api

 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 

二、字符串格式化app

格式說明由「%」和格式字符組成,如%d%f等。它的做用是將輸出的數據轉換爲指定的格式輸出。ide

%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

三、字符定義

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:符號

四、字符串拼接

 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

五、獲取字符串中指定索引處的字符

每一個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 }

六、字符串插入

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

七、字符串刪除

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

注意(總結六、字符串插入和七、字符串刪除):

使用insert(_:at:),insert(contentsOf:at:),remove(at:),和removeSubrange(_:),對符合任何類型的方法RangeReplaceableCollection的協議。

這包括String以及集合類型,如Array,Dictionary和Set。

八、獲取字符串長度

1 var str = "Strengthen"
2 print(str.count)
3 //Print 10

九、字符串比較
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

十、檢查字字符串前綴
檢查字符串是否具備特定的字符串前綴調用字符串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"

十一、檢查字符串後綴
檢查字符串是否具備特定的字符串後綴調用字符串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"    

十二、字符串包含

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

1三、查找字符

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

1四、截取字符串
字符串和子字符串之間的區別在於,做爲性能優化,子字符串能夠重用用於存儲原始字符串的部份內存,或者用於存儲另外一個子字符串的內存的一部分。

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)

1五、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

1六、字符串分割

 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})
13 let str4 = arrayStr.reduce("-", {$0 + $1})
14 print("\(str3) ", terminator: "")
15 print("\(str4) ", terminator: "")
16 //strengthen!
17 //-strengthen!
18 
19 /*整數數組轉字符串*/
20 let arrayInt = [0,1,2,3,4,5,6,7,8,9]
21 let dataInt = arrayInt.map(String.init)
22 let strInt = dataInt.joined(separator: "-")
23 print("\(strInt) ", terminator: "")
24 //0-1-2-3-4-5-6-7-8-9

1七、字符串替換replacingOccurrences
(1)、簡單替換

1 //原始字符串
2 let str1 = "strengthen"
3 //替換後的字符串
4 let str2 = str1.replacingOccurrences(of: "en", with: "ne")
5 print(str2)
6 //Print strnegthne

(2)、使用正則表達式替換

 1 extension String {
 2     //使用正則表達式替換
 3     func pregReplace(pattern: String, with: String,options: NSRegularExpression.Options = []) -> String {
 4         let regex = try! NSRegularExpression(pattern: pattern, options: options)
 5         return regex.stringByReplacingMatches(in: self, 
 6                                          options: [],
 7                                            range:NSMakeRange(0, self.count),
 8                                     withTemplate: with)
 9     }
10 }

1八、string轉換爲Int/Long/Float/Double/Bool等

 1 var str1="100"
 2 var num1=(str1 as NSString).integerValue
 3 print(num1)
 4 //Print 100
 5 var num2=(str1 as NSString).intValue
 6 print(num2)
 7 //Print 100
 8 var num3=(str1 as NSString).longLongValue
 9 print(num3)
10 //Print 100
11 var str2="10.8888888"
12 var num4=(str2 as NSString).floatValue
13 print(num4)
14 //Print 10.888889
15 var num5=(str2 as NSString).doubleValue
16 print(num5)
17 //Print 10.8888888
18 var str3="true"
19 var num6=(str3 as NSString).boolValue
20 print(num6)
21 //Print true

1九、反轉字符串

 1 var str = "strengthen"
 2 //不修改原字符串
 3 str.reversed()
 4 print(str)
 5 //Print strengthen
 6 
 7 //注意轉換爲字符串
 8 //str.reversed()爲ReversedCollection<String>(_base: "strengthen")
 9 print(String(str.reversed()))
10 //Print nehtgnerts

20、字符串遍歷,枚舉字符
請參考本博客另外一篇技術博文:《[Swift]遍歷字符串》


2一、首字母大寫、轉換爲大寫字母、轉換爲小寫字母
請參考本博客另外一篇技術博文:《[Swift]字符串大小寫轉換,同時實現本地化或設置語言環境》


2二、使用NSString對字符串進行各類操做
請參考本博客另外一篇技術博文:[Swift4.2實際操做]7、常見概念-(5)使用NSString對字符串進行各類操做

 

2三、添加指定個數的字符

字符串自己就是字符的數組,因此能夠利用數組的定義形式去定義字符串。

1 var str:String = String()
2 str.append(String(repeating:"S",count:10))
3 print(str)
4 //Print SSSSSSSSSS
相關文章
相關標籤/搜索