Swift中获取字符串和字符串比较

子字符串

  • 使用下标或者类似 prefix(_:) 的方法得到的字符串是 Substring 类型
  • Substring 拥有 String 的大部分方法
  • Substring 可以转换成 String 类型
let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..
  • 子字符串重用一部分原字符串的内存
  • 修改字符串或者子字符串之前都不需要花费拷贝内存的代价
  • String 和 Substring 都遵循 StringProtocol 协议,也就是说它基本上能很方便地兼容所有接受 StringProtocol 值的字符串操作函数


    子字符串.png

字符串比较

  • 字符串和字符相等性(== 和!=)
  • 前缀相等性 (hasPrefix(_:))
  • 后缀相等性(hasSuffix(_:))
var welcome = "hello, "
var welcome1 = "hello"
print(welcome == welcome1)
print(welcome.hasPrefix("hello"))
print(welcome.hasSuffix("world"))

打印结果如下:
false
true
false

你可能感兴趣的:(Swift中获取字符串和字符串比较)