Swift -字符串

//: Playground - noun: a place where people can playapi

 

import UIKitapp

 

var str = "Hello, playground"spa

 

 

//字符串orm

//空字符串字符串

var emptyString = ""string

var emptyString2 = String ()it

 

//空字符串的判斷form

emptyString.isEmptyclass

str.isEmptyimport

 

let mark = "!!!"

str + mark

str

 

str += mark

str

 

//

 

let name = "liuyubobobo"

let age = 16

let height = 1.78

let s = "My name is \(name). I'm \(age) years old . I'm \(height) meter tall."

print(s)

 

//

for c in str.characters {

    print(c)

}

 

//字符

str

let mark:Character = "!"

str.append(mark)

str

 

 

//string.characters

let englishLetter:Character = "a"

let chineseLetter:Character = ""

let dog:Character = "🐩"

 

let collGuy:Character = "\u{1F60E}"

 

var collLetters = "abc"

collLetters.characters.count

 

var collGuys = "\u{1F60E}\u{1F60E}\u{1F60E}"

collGuys.characters.count

 

var cafe = "cafe\u{0301}"

cafe.characters.count

 

 

//string.index

let starIndex = str.startIndex

starIndex

 

str[starIndex]

 

let index = str.index(starIndex, offsetBy: 4)

index

str[index]

 

 

let endIndex = str.endIndex

//[starIndex, endIndex) endIndex 其實不是最後一個字符的位置,而是最後一個字符後面的位置

str.index(before: endIndex) //表示最後一個字符

 

 

//range

let range = starIndex..<index

 

 

str.replaceSubrange(range, with: "HI")

str

 

//字符串的一些方法

str.uppercased()//轉爲大寫

str.lowercased()//轉爲小寫

str.capitalized//將首字母大寫

 

str.contains("Hello")//判斷是否包含改字符串

str.hasPrefix("He")//判斷是否以該字符串開頭

str.hasSuffix("fr")//判斷是否以改字符串結尾

 

//NSString

let s2:String = NSString.init(format: "one third is %.2f",1.0/3.0) as String//Nsstring轉換爲String

s2

 

var s3:NSString = "one third is 0.33"

s3.substring(from: 4)

s3.substring(to: 3)

s3.substring(with: NSMakeRange(4, 5))

 

//去除指定的字符

let s4 = "------  Hello ----" as NSString

s4.trimmingCharacters(in: CharacterSet.init(charactersIn: " -"))

相關文章
相關標籤/搜索