Swift -字符串

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

 

import UIKit

 

var str = "Hello, playground"

 

 

//字符串

//空字符串

var emptyString = ""

var emptyString2 = String ()

 

//空字符串的判断

emptyString.isEmpty

str.isEmpty

 

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: " -"))

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2016-11-02 11:40  一枚IT女  阅读(260)  评论(0编辑  收藏  举报