Swift 字符和字符串

字符串定义

import UIKit

// 字符串定义
var emptyString = ""
var anotherEmptyString = String()

if emptyString.isEmpty {
    print("Nothing to see here")
}

单个字符访问字符串

// 单个字符访问字符串
var dogString = "Dog!"
for character in dogString.characters {
    print(character)
}

字符串的拼接

// 字符串拼接
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
print(welcome)

var instruction = "look over"
instruction += string2
print(instruction)

// 字符串拼接单个字符
let exclamationMark : Character = "!"
welcome.append(exclamationMark)
print(welcome)

字符串Unicode 展现

// 字符串Unicode 展现
var sayHi = "Hi 你好 \u{1F496}"

// UTF-8编码展示
print("UTF-8编码")
for utf8Character in sayHi.utf8 {
    print("\(utf8Character) ", terminator: "")
}

// UTF-16编码展示
print("\nUTF-16编码")
for utf16Character in sayHi.utf16{
    print("\(utf16Character) ", terminator: "")
}

// Unicode(UTF-32)编码展示
print("\nUnicode(UTF-32)编码")
for unicodeCharacter in sayHi.unicodeScalars {
    print("\(unicodeCharacter.value) ", terminator: "")
}

console log输入结果如下:


屏幕快照 2016-08-03 下午3.54.57.png

字符串个数

// 字符串个数
var word = "cafe"
print("")
print("the number of characters in \(word) is \(word.characters.count)")

字符串比较

// 字符串比较
let quotation = "We're a lot alike, you and I"
let sameQuotation = "We're a lot alike, you and I"
if quotation == sameQuotation {
    print("These two strings are considered equal")
}

var oneSong = "开心马骝.mp3"
// 前缀
if oneSong.hasPrefix("开心") {
    print("\(oneSong) 有前缀开心")
}

// 后缀
if oneSong.hasSuffix("mp3") {
    print("\(oneSong) 是一首歌")
}

console log输入结果如下:


屏幕快照 2016-08-03 下午4.00.33.png

你可能感兴趣的:(Swift 字符和字符串)