//
// main.swift
// Swift
//
// Created by 空想家 on 16/7/1.
// Copyright © 2016年 kongxiangjia. All rights reserved.
//
import Foundation
print("Hello, World!")
let someString = "Some string leteral value"
var emptyString = ""
var anotherEmptyString = String()
if emptyString.isEmpty {
print("emptyString isEmpty")
}
// 字符串可变性
var variableString = "variable"
variableString += "String"
print(variableString)
// 操作字符
for character in "There".characters{
// print(character)
print(character)
}
// String值可以通过传入 Character值的字符串作为实际参数到它的初始化器来构造:
let catCharacters:[Character] = ["C","a","t"]
let catString = String(catCharacters)
print(catString)
// 连接字符串和字符
let string1 = "Hello"
let string2 = " look"
var hw = string1 + string2
print(string2 + string1)
var h = " there"
hw += h
print(hw)
let exclmaionMark:Character = "!"
hw.append(exclmaionMark)
hw.append(exclmaionMark)
print(hw)
// 字符串插值
let multiplier = "3"
/*
2.2 语法
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
*/
// 3.0语法
let message = "\(multiplier) times 2.5 is \(Double(multiplier)! * 2.5)"
print(message)
// 扩展字形集群
let eAcute: Character = "\u{E9}" // é
let combinedEAcute:Character = "\u{65}\u{301}" // e followed by ́
print(eAcute,combinedEAcute)
// 字符串统计
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
print("unusualMenagerie has \(unusualMenagerie.characters.count) characters")
let kaola = "🐨"
print("🐨 has\(kaola.characters.count)")
// 访问和修改字符串
// 字符串索引
let greeting = "Guten Tag!"
let firstWordOfGreeting = greeting[greeting.startIndex]
print(firstWordOfGreeting)
let lastWordOfGreeting = greeting[greeting.index(before: greeting.endIndex)]
print(lastWordOfGreeting)
let index = greeting.index(greeting.startIndex, offsetBy: 2)
print(greeting[index])
for index in greeting.characters.indices {
// print("\(greeting[index])",index)
print(index)
// terminator 终结
// print("\(greeting[index]) ", terminator: "")
}
var str = "Hello"
for (index, string) in str.characters.enumerated() {
print("index = \(index), string = \(string)")
}
// 插入删除字符串
var welcome = "hello"
// 插入单个字符
welcome.insert("!", at: welcome.endIndex)
// 插入字符串
welcome.insert(contentsOf:"插入字符串".characters, at: welcome.startIndex)
print(welcome)
// 删除某个字符
welcome.remove(at: welcome.index(before: welcome.endIndex))
print(welcome)
// 删除某段字符串
let range = welcome.index(welcome.startIndex, offsetBy: 4)..
网友评论