Swift学习笔记——字符串的使用

Swift学习笔记——字符串的使用,第1张

在Swift中,字符串是值类型。

1、String值在传递给方法或者函数的时候会被复制过去
2、赋值给常量或者变量的时候也是一样
3、Swift编译器优化了字符串使用的资源,实际上拷贝只会在确实需要的时候才进行

示例代码:

let mulStr = 3
let msg = "\(mulStr) times 2.5 is \(Double(mulStr) * 2.5)"
字符串拼接

1、使用加运算符(+)创建新字符串
2、使用加赋值符号(+=)在已经存在的String值末尾追加一个String值
3、使用String类型的append()方法来可以给一个String变量的末尾追加字符值

示例代码:

var welcome = "hello"
welcome += "world"
welcome.append(",")
字符串插值

1、字符串插值是一种从混合常量、变量、字面量和表达式的字符串字面量构造新string值的方法
2、每一个你插入到字符串字面量的元素都要被一对圆括号包裹,然后使用反斜杠前缀
3、类似于NSString的stringWithFormat方法,但是更加简便,更强大

示例代码:

let str = "6 * 7 = \(6*7)"
字符串索引

1、每一个String值都有相关的索引类型,String.index,相当于每个字符在字符串中的位置
2、startIndex代表字符串第一位,endIndex代表字符串最后一个字符后的位置,所以,endIndex属性并不是字符串下标脚本的合法实际参数
3、如果空字符串,则startIndex = endIndex
4、使用index(before:)、index(after:)方法来访问给定索引的前后
5、要访问给定索引更远的索引,使用index(_:offsetBy:)
6、使用indices属性来访问字符串中每个字符的索引

示例代码:
let greeting = "hello world!"
print(greeting[greeting.startIndex])
print(greeting[greeting.index(before: greeting.endIndex)])
print(greeting[greeting.index(after: greeting.startIndex)])
let index = greeting.index(greeting.startIndex, offsetBy: 7)
print(greeting[index])

打印结果:
h
!
e
o
插入/删除字符

1、插入字符:insert(:at:)方法
2、插入另一个字符串的内容到特定的索引,使用insert(contentsOf:at:)方法
3、移除字符:remove(at:)方法
4、移除一小段特定范围的字符串,使用removeSubrange(
:)方法


var welcom = "hello"
welcom.insert("!", at: welcom.endIndex)
welcom.insert(contentsOf: "world", at: welcom.index(before:welcom.endIndex))
print(welcom)

welcom.remove(at: welcom.index(before: welcom.endIndex))
print(welcom)
let range = welcom.index(welcom.endIndex,offsetBy:-5)..<welcom.endIndex
welcom.removeSubrange(range)
print(welcom)

打印结果:
helloworld!
helloworld
hello
子字符串

1、使用下标或者类似prefix(_:)的方法得到的子字符串是Substring类型
2、Substring拥有String的大部分方法
3、Substring可以转成String类型

子字符串会重用一部分原字符串的内存;
修改字符串或者子字符串之前都不需要花费拷贝内存的代价;
String 和 Substring 都遵循 StringProtocol协议,它基本上可以很方便地兼容所有接受StringProtocol值的字符串 *** 作函数。

let greeting = "hello, world!";//String常量
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex//索引
let begin = greeting[..<index]//SubString类型
let newStr = String(begin)//SubString转成String
print(begin)
print(newStr)

打印结果:
hello
hello
字符串比较
1、字符串和字符相等(==!=2、前缀相等 hasPrefix(_:)
3、后缀相等 hasSuffix(_:)

示例代码:
let greeting = "hello, world!";//String常量
let welcome = "hello"
print(greeting == welcome)
print(greeting.hasPrefix("hello"))
print(greeting.hasSuffix("world"))
print(welcome.hasSuffix("world"))

打印结果:
hello
hello
false
true
false
false

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/996746.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存