var a = "he l lo" print(a.count) // 計算空格,輸出7
String.Index類型表示字符串內某一個字符的位置。swift
能夠利用a[String.Index]來獲取某一個位置的字符。app
var a = "hello" print(a.startIndex) // 輸出Index(_rawBits: 1) print(a[a.startIndex]) // 獲取字符串第一位,輸出h
如何輸出最後一位呢?code
print(a[a.endIndex]) // 報錯,由於endIndex的位置是字符串的結束符,並非看到的最後一個字符
ci
能夠用a.index(before: String.Index)
和a.index(after: String.Index)
分別獲取某一個位置的前一位和後一位。rem
a[a.index(before: a.endIndex)]
就能夠獲取到字符串最後一個字符。字符串
如何輸出指定的某一位?string
a[a.index(a.startIndex, offsetBy: 2)]
,意爲:從a.startIndex開始,日後數兩位。it
若是offsetBy後面使用了一個負數,那麼就是從後往前數。io
輸出某一段的字符for循環
var begin = a.index(a.startIndex, offsetBy: 1) var end = a.index(a.startIndex, offsetBy:4) print(str[begin...end]) // 輸出ello
或者使用prefix(Int)方法來獲取前n個字符:
var str = a.prefix(2) print(str) // 輸出he
如何找到第一次出現某字符的位置
a.firstIndex(of: "e")
判斷字符是否在字符串中
使用contains(Char)
方法:(大小寫敏感)
var str = "hello" print(str.contains("h")) // true print(str.contains("hel")) // true
也能夠使用contains(where: String.contains(""))
方法:(這種方法只要有一個包含就返回真值)
var str = "hello" print(str.contains(where: String.contains("ae"))) // true
判斷字符串的開頭或結尾是不是某字符
可以使用hasPrefix("")
判斷開頭
var str = "hello" print(str.hasPrefix("h")) // true print(str.hasPrefix("he")) // true print(str.hasPrefix("e")) // false
使用hasSuffix()
判斷結尾
var str = "hello" print(str.hasPrefix("o")) // true print(str.hasPrefix("lo")) // true print(str.hasPrefix("ol")) // false
字符串結尾增長新字符串
append()
便可:
var str = "hello" str.append(" world") // hello world
在某個位置增長某段字符串
insert(contentsOf: str, at: String.Index)
能夠在at位置的前面插入str:
var str = "hello" str.insert(contentsOf: "AAA", at: str.startIndex) // AAAhello
替換某一字段
replaceSubrange(section, with: "lalala")
section是String.Index的區間範圍,替換爲"lalala":
var str = "hello" let section = str.startIndex...str.index(str.endIndex, offsetBy: -2) str.replaceSubrange(section, with: "lalala") // "lalalao"
也能夠使用replacingOccurrences(of: str, with: "jj")
將str字段替換爲"jj":
var str = "hello" str.replacingOccurrences(of: "ll", with: "jj") // "hejjo"
若是沒有該字段,則不替換
刪除某位置的字符
remove(at: String.Index)
var str = "hello" str.remove(at: str.index(str.startIndex, offsetBy: 2)) // l print(str) // helo
刪除某字段
removeSubrange(String.Index...String.Index)
var str = "hello" str.removeSubrange(str.startIndex...str.index(str.endIndex, offsetBy: -2)) print(str) // o
直接遍歷
var str = "hello" for item in str { print(item) }
使用index()方法來遍歷
var str = "hello" for item in 0..<str.count { print(str[str.index(str.startIndex, offsetBy: item)]) }