字符串和字符

12 篇文章 0 订阅

字符串和字符

字符串字面量

字符串字面量是被双引号 " 包裹的固定顺序文本字符。使用字符串字面量作为常量或变量的初始值。

let someString = "Some string literal value"

如果你需要很多行的字符串,使用多行字符串字面量。多行字符串字面量是用三个双引号引起来的一系列字符:

let quotation = """
The White Rabbit put on his spectacles.  "Where shall I begin,
please your Majesty?" he asked.
 
"Begin at the beginning," the King said gravely, "and go on
till you come to the end; then stop."
"""

由于多行用了三个双引号而不是一个,你可以在多行字面量中使用单个双引号 "。要在多行字符串中包含 """,你必须用反斜杠\ 转义至少其中一个双引号

要让多行字符串字面量开始或结束带有换行,写一个空行作为第一行或者是最后一行。

"""
 
This string starts with a line feed.
It also ends with a line feed.
 
"""

多行字符串可以缩进以匹配周围的代码。双引号 """ 前的空格会告诉 Swift 其他行前应该有多少空白是需要忽略的.

初始化字空符串

初始化一个空字符串有两种方式:
1、赋值一个空的字符串字面量给变量
2、使用初始化器语法来初始化一个新的 String实例

var emptyString = ""               // empty string literal
var anotherEmptyString = String()  // initializer syntax
// these two strings are both empty, and are equivalent to each other

通过布尔值 isEmpty 属性来检测字符串的值是否为空

if emptyString.isEmpty {
    print("Nothing to see here")
}
// prints "Nothing to see here"
可变字符串

你可以通过把一个 String 设置为变量(可被修改),或者为常量(不能被修改)来指定它是否可以被修改。可以使用 + 来连接两个字符串。

var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"
 
let constantString = "Highlander"
constantString += " and another Highlander"
// this reports a compile-time error - a constant string cannot be modified
操作字符串

通过 for-in 循环遍历 String 中的每一个独立的 Character 值:

for character in "Dog!?" {
    print(character)
}

另外,你可以通过提供Character类型标注来从单个字符的字符串字面量创建一个独立的Character常量或者变量:

连接字符串或字符

String值能够被加起来(或者说连接),使用加运算符 + 来创建新的String值:

let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"

也可以使用加赋值符号 += 在已经存在的 String值末尾追加一个 String值:

var instruction = "look over"
instruction += string2
// instruction now equals "look over there"

你使用 String 类型的 append() 方法来可以给一个 String 变量的末尾追加 Character 值:

let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
字符串插值
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
字符串字面量中的特殊字符
  • 转义特殊字符 \0 (空字符), \ (反斜杠), \t (水平制表符), \n (换行符), \r(回车符), " (双引号) 以及 \' (单引号);

  • 任意的 Unicode 标量,写作 \u{n},里边的 n是一个 1-8 个与合法 Unicode 码位相等的16进制数字。

字符串统计

要在字符串中取回 Character 值的总数,使用字符串的 count 属性:

let unusualMenagerie = "Koala ?, Snail ?, Penguin ?, Dromedary ?"
print("unusualMenagerie has \(unusualMenagerie.count) characters")
// Prints "unusualMenagerie has 40 characters"
访问和修改字符串

你可以通过下标脚本语法或者它自身的属性和方法来访问和修改字符串。

字符串索引 (截取)
  • 每一个 String值都有相关的索引类型,String.Index,它相当于每个 Character 在字符串中的位置。

  • 使用 startIndex属性来访问 String 中第一个 Character 的位置。 endIndex 属性就是 String 中最后一个字符后的位置。所以说,endIndex 属性并不是字符串下标脚本的合法实际参数。如果 String 为空,则 startIndexendIndex 相等。

  • 使用 index(before:)index(after:) 方法来访问给定索引的前后。要访问给定索引更远的索引,你可以使用 index(_:offsetBy:) 方法。

let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G
greeting[greeting.index(before: greeting.endIndex)]
// !
greeting[greeting.index(after: greeting.startIndex)]
// u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// a
  • 使用 characters 属性的 indices 属性来创建所有能够用来访问字符串中独立字符的索引范围 Range
for index in greeting.characters.indices {
    print("\(greeting[index]) ", terminator: "")
}
插入和删除
  • 要给字符串的特定索引位置插入字符,使用 insert(_:at:) 方法,另外要冲入另一个字符串的内容到特定的索引,使用 insert(contentsOf:at:) 方法。
var welcome = "hello"
welcome.insert(" ", at: welcome.endIndex)
welcome.insert(contentsOf: "world", at: welcome.endIndex)
  • 要从字符串的特定索引位置移除字符,使用 remove(at:) 方法,另外要移除一小段特定范围的字符串,使用 removeSubrange(_:) 方法:
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there"
 
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome now equals "hello"
字符串比较
  • 字符串和字符相等使用“等于”运算符 == 和“不等”运算符 != 进行检查:
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")
}
// prints "These two strings are considered equal"
  • 要检查一个字符串是否拥有特定的字符串前缀或者后缀,调用字符串的 hasPrefix(_:)hasSuffix(_:) 方法,它们两个都会接受一个 String 类型的实际参数并且返回一个布尔量值。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值