swift篇 基础知识5 -- 字符串(String)和字符(character)

 

字符串字面量

多行字符串字面量

如果你需要一个字符串是跨越多行的,那就使用多行字符串字面量 — 由一对三个双引号包裹着的具有固定顺序的文本字符集:

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."
"""

如果你不想换行,可以用在行尾写一个反斜杠(\)作为续行符。

let softWrappedQuotation = """
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."
"""

以上代码效果如下:

字符串字面量的特殊字符

字符串字面量可以包含以下特殊字符:

  • 转义字符 \0(空字符)、\\(反斜线)、\t(水平制表符)、\n(换行符)、\r(回车符)、\"(双引号)、\'(单引号)。
  • Unicode 标量,写成 \u{n}(u 为小写),其中 n 为任意一到八位十六进制数且可用的 Unicode 位码。

下面的代码为各种特殊字符的使用示例。 wiseWords 常量包含了两个双引号。 dollarSignblackHeart 和 sparklingHeart 常量演示了三种不同格式的 Unicode 标量:

let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imageination is more important than knowledge" - Enistein
let dollarSign = "\u{24}"             // $,Unicode 标量 U+0024
let blackHeart = "\u{2665}"           // ♥,Unicode 标量 U+2665
let sparklingHeart = "\u{1F496}"      // 💖,Unicode 标量 U+1F496

扩展字符串分隔符

扩展分隔符创建的字符串文字也可以是多行字符串文字。 您可以使用扩展分隔符在多行字符串中包含文本 """覆盖原有的结束文字的默认行为(在#...#中任何形式都可以默认)。例如:

let threeMoreDoubleQuotationMarks = #"""
Here are three more double quotes: """
"""#

初始化空字符串

要创建一个空字符串作为初始值,可以将空的字符串字面量赋值给变量,也可以初始化一个新的 String 实例:

var emptyString = ""               // 空字符串字面量
var anotherEmptyString = String()  // 初始化方法
// 两个字符串均为空并等价。

你可以通过检查 Bool 类型的 isEmpty 属性来判断该字符串是否为空:

if emptyString.isEmpty {
    print("Nothing to see here")
}
// 打印输出:“Nothing to see here”

字符串可变性

你可以通过将一个特定字符串分配给一个变量来对其进行修改,或者分配给一个常量来保证其不会被修改:

var variableString = "Horse is hello"
variableString += " and carriage"
// variableString 现在为 "Horse and carriage"

var message : String = "Horse"
message.uppercased() 
//将字符串转换成大写模式
message.lowercased()
//将字符串转换成小写模式
message.capitalized
//将字符串中的单词的首字母,转换成大写模式

//将字符串按照指定的内容进行分隔,并返回一个数组
message.components(separatedBy:" ")
//将两字符串比较,不区分大小写
message.caseInsensitiveCompare("horse is hello").rawValue //0(两相同),-1、-2...-n(不同,且前者比后者短n位),1、2...n(不同,且前者比后者长n位)

字符串是值类型

 

使用字符

你可通过 for-in 循环来遍历字符串,获取字符串中每一个字符的值:

for character in "Dog!🐶" {
    print(character)
}
// D
// o
// g
// !
// 🐶

for-in 循环在 For 循环 中进行了详细描述。

另外,通过标明一个 Character 类型并用字符字面量进行赋值,可以建立一个独立的字符常量或变量:

let exclamationMark: Character = "!"

字符串可以通过传递一个值类型为 Character 的数组作为自变量来初始化:

let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString)
// 打印输出:“Cat!🐱”

连接字符串和字符

字符串可以通过加法运算符(+)相加在一起(或称“连接”)创建一个新的字符串:

let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome 现在等于 "hello there"

你也可以通过加法赋值运算符(+=)将一个字符串添加到一个已经存在字符串变量上:

var instruction = "look over"
instruction += string2
// instruction 现在等于 "look over there"

你可以用 append() 方法将一个字符附加到一个字符串变量的尾部:

let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome 现在等于 "hello there!"

注意

你不能将一个字符串或者字符添加到一个已经存在的字符变量上,因为字符变量只能包含一个字符。

字符串插值

字符串插值是一种构建新字符串的方式,可以在其中包含常量、变量、字面量和表达式。字符串字面量多行字符串字面量都可以使用字符串插值。你插入的字符串字面量的每一项都在以反斜线为前缀的圆括号中:

let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message 是 "3 times 2.5 is 7.5"

计算字符数量

如果想要获得一个字符串中 Character 值的数量,可以使用 count 属性

let cont = "String"
// 6

访问和修改字符串

字符串索引

使用 startIndex 属性可以获取一个 String 的第一个 Character 的索引。

使用 endIndex 属性可以获取最后一个 Character 的后一个位置的索引。因此,endIndex 属性不能作为一个字符串的有效下标。

如果 String 是空串,startIndex 和 endIndex 是相等的。

通过调用 String 的 index(before:) 或 index(after:) 方法,可以立即得到前面或后面的一个索引。

你还可以通过调用 index(_:offsetBy:) 方法来获取对应偏移量的索引,这种方式可以避免多次调用 index(before:) 或 index(after:) 方法。

具体用法如下:

let aa = "Guten Tag!"
aa[aa.startIndex] //字符串的开始字符
// G
aa[aa.index(before: aa.endIndex)]  //字符串的长度-1的字符
// !
aa[aa.index(after: aa.startIndex)]  //字符串的开始字符之后的字符
// u 
let index = aa.index(aa.startIndex, offsetBy: 7) //字符串开始字符之后的第7个字符
// 整体上是字符串的第7+1个字符

aa[index]
// a

超出范围错误

aa[aa.endIndex] // error
aa.index(after: endIndex) // error

使用 indices 属性会创建一个包含全部索引的范围(Range),用来在一个字符串中访问单个字符。

for index in aa.indices {
   print("\(aa[index]) ", terminator: "")//terminator 不换行
}
// G u t e n   T a g ! 

插入和删除

调用 insert(_:at:) 方法可以在一个字符串的指定索引插入一个字符,调用 insert(contentsOf:at:) 方法可以在一个字符串的指定索引插入一个段字符串。

var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome 变量现在等于 "hello!"

welcome.insert(contentsOf:" there", at: welcome.index(before: welcome.endIndex))
// welcome 变量现在等于 "hello there!"

调用 remove(at:) 方法可以在一个字符串的指定索引删除一个字符,调用 removeSubrange(_:) 方法可以在一个字符串的指定索引删除一个子字符串。

welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome 现在等于 "hello there"

let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome 现在等于 "hello"

子字符串

当你从字符串中获取一个子字符串 —— 例如,使用下标或者 prefix(_:) 之类的方法 —— 就可以得到一个 SubString 的实例,而非另外一个 String

Swift 里的 SubString 绝大部分函数都跟 String 一样,意味着你可以使用同样的方式去操作 SubString 和 String

然而,跟 String 不同的是,你只有在短时间内需要操作字符串时,才会使用 SubString

当你需要长时间保存结果时,就把 SubString 转化为 String 的实例:

let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning 的值为 "Hello"

// 把结果转化为 String 以便长期存储。
let newString = String(beginning)

 比较字符串

字符串/字符相等

字符串/字符可以用等于操作符(==)和不等于操作符(!=),

前缀/后缀相等

通过调用字符串的 hasPrefix(_:)/hasSuffix(_:) 方法来检查字符串是否拥有特定前缀/后缀,两个方法均接收一个 String 类型的参数,并返回一个布尔值。

contains判断字符串是否包含另一个字符串

var message = " hello world!!"
message.contains("hello") //true

distance判断字符串中的两个索引之间的距离

var message1 : String = "hello world!"

message1.distance(from: message1.startIndex, to: message1.endIndex)
//12

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值