swift3 0 String 字串 的使用

2021-08-15 07:58:24 字數 3296 閱讀 5217

var emptystring = ""               // 空字串字面量

var anotheremptystring = string() // 初始化方法

// 兩個字串均為空並等價。

var variablestring = "horse"

variablestring += " and carriage"

// variablestring 現在為 "horse and carriage"

let oranges = 8

let lable = "the width is"

let val = 66

let lablewidth = lable + string(val)//swift不支援隱式型別轉換,需顯式轉換

let money :character = "¥"

let face:character = "?"

print("\(money) \(face)")

/*字串常量包含的特殊字元:空字元\0,反斜槓\,製表符\t,換行符\n,回車符\r,雙引號\",單引號\'*/

let countstr = "wo shi sha sha de "

print("count's count is \(countstr.characters.count)")//算上空格

var str00 = "i am string"

let str01 = ""

let str02 = "我是字串"

str00.isempty
獲取字串字元數量

str01.characters.count
檢查字串是否含有特定的字首/字尾

str00.hasprefix("i")//字首

str00.hassuffix("i")//字尾

大小寫字母轉換

str00.uppercased()

str00.lowercased()

str02.uppercased()//中文進行大小寫轉換不起作用

str00.capitalized

字串擷取

(str00 as nsstring).substring(to: 4)//留下字串前4個字母

(str00 as nsstring).substring(from: 4)//不要前4個字母

(str00 as nsstring).substring(with: nsmakerange(2, 2))

去除字串最後的字母或首字母

let index0 = str00.index(before: str00.endindex)

let index1 = str00.index(after: str00.startindex)

str00.remove(at:index0)

str00.remove(at: index1)

獲取某個子串在父串中的範圍

str00.range(of: "am")
字串轉為陣列

let str3 = "10:20:c:d:e"

let result = str3.components(separatedby:":")

字串轉為[character]

let characters = str3.sorted()
指定範圍內的字串替換為其他字串,將cde替換成m,使輸出結果為abmfghi

let str4 = "abcdefghi"

let startindex = str4.index(str4.startindex, offsetby:2)

let endindex = str4.index(startindex, offsetby:3)

let result4 = str4.replacingcharacters(in:startindex..int轉16進製制字串

int轉8進製字串

16進製制字串轉十進位制數

func strhextoint()   

}}

string轉換成為int8

func stringtoint(str: string) -> array

return arr

}

把字串前後的空格或換行符去掉

var tempstr = "  he ll o \r\r"

let str = tempstr.trimmingcharacters(in: .whitespacesandnewlines)//"hello"

遇到空格或換行的地方把字串拆開

var temparray = readclientdatastring!.components(separatedby: .whitespacesandnewlines)
去除陣列中的""

temparray = temparray.filter
字串替換volume -> v

var str = "hello s"

let strreplaced = str.replacingoccurrences(of: "s", with: "amberoot")//"hello amberoot"

將十六進製制數字轉換為int

let intdata = nsstring(format: "%d", 0x10).integervalue//16

Swift 獲得字串String長度

在objective c中我們通常使用length來獲取nsstring型別的字串的長度,而在swift中,string結構體沒有了這個方法,那怎樣獲取string型別的字串的長度呢?我們可以通過他的擴充套件屬性成員characters的count屬性來獲取 let titlestring stri...

窺探Swift之字串(String)

之前總結過objective c中的字串 objective c精選字串處理方法 學習一門新語言怎麼能少的了字串呢。swift中的string和objective c語言中nsstring還是區別不小的,swift中的string又回歸了正常狀態,使用起來更為方便快捷。本篇部落格的主題就是swift...

swift3 0 關於字串

playground noun a place where people can play import uikit 字串字面量 func zfczml unicode 標量 u 0024 u unicode 標量 u 2665 u unicode 標量 u 1f496 初始化空字串 func cs...