1.字符
在Swift中字符类型是Character。与其他的类型申明类似,我们可以指定变量或常量类型为Character,但是如果省略Character类型的声明,编译器自动推断出的类型不是字符类型,而是字符串类型。
let andSign1 = "&" //编译器自动推断为字符串类型
字符类型表示时也是放到双引号(")中,但一定是一个字符,如下语句会出现编译错误:
let andSign1: Character = "&A" //会发生编译错误
下面是字符的正确写法:
let andSgin1: Character = "&"
let andSgin2: Character = "\u{26}" //表示一个字符可以使用字符本身,也可以使用它的Unicode编码
let lamda1: Character = "λ"
let lamda2: Character = "\u{03bb}"
2.字符串
字符串的创建:
let str = "hello world"
print("字符串的长度:\(str.characters.count)")
var emptyString1 = "" //可变字符串
var emptyString2 = String() //可变字符串 调用了String 的构造函数
字符串的拼接:
var ChineseZodiac = "鼠牛"
ChineseZodiac = ChineseZodiac + "虎"
ChineseZodiac += "兔"
let yang:Character = "羊"
ChineseZodiac.append(yang)
字符串插入、删除和替换
String 提供的API:
//在索引位置插入字符
func insert(_ newElement:Character,at i:String.Index)
//在索引位置删除字符
func remove(at i:String.Index) -> Character
//删除指定范围内的字符串
func removeSubrange(_ bounds: Range<String.Index>)
//使用字符串或者字符替换指定范围内的字符
func replaceSubrange(_ bounds: ClosedRange<Substring.Index>, with newElements: Substring)
示例代码如下:
var str = "Objective-C and Swift"
print("原始字符串:\(str)")
str.insert(".",at:str.endIndex)
print("插入.字符后:\(str)")
str.remove(at:str.index(before:str.endIndex))
print("删除.字符后:\(str)")
var startIndex = str.startIndex
var endIndex = str.index(startIndex,offsetBy:9)
var range = startIndex...endIndex
str.removeSubrange(range)
print("删除范围后:\(str)")
endIndex = str.index(startIndex,offsetBy:0)
range = startIndex...endIndex
str.replaceSubrange(range,with:"C++")
print("替换范围后:\(str)")
输出结果:
原始字符串:Objective-C and Swift
插入.字符后:Objective-C and Swift.
删除.字符后:Objective-C and Swift
删除范围后:C and Swift
替换范围后:C++ and Swift
3.控制语句
分支语句:if、switch、guard。
循环语句:white、repeat-white和for。
跳转语句:break、continue、fallthrough、return和throw。
网友评论