swift 中 7 种获取字符串前缀的方法

点击下方公众号卡片,关注我,每天分享一个关于 iOS 的新知识

前言

在日常的开发中,经常会需要获取一个字符串的前缀,我总结了在 Swift 中检查字符串前缀的多种方法分享给大家,看看有没有你不知道的。

我们以为 "Hello World" 这个字符串为例,判断是否以 Hello 开头。

1. 使用 hasPrefix(_:) 方法

可以使用字符串的 hasPrefix(_:) 方法检查字符串是否有指定的前缀:

javascript 复制代码
let str = "Hello World"
if str.hasPrefix("Hello") { // true
    print("\(str) 以 Hello 开头")
} 

这个方法直接返回一个 Bool 来判断是否以某个字符串开头。

2. prefix 函数获取前缀子字符串

可以使用 prefix(_:) 来获取前缀子字符串:

swift 复制代码
let str = "Hello World"
let prefix = str.prefix(5)
if prefix == "Hello" { 
    print("\(str) 以 Hello 开头")
} 

这种方法利用 prefix 函数获取前 5 个字符,然后再与 "Hello" 做对比。

3. prefix(upTo:) 函数获取前缀子字符串

可以使用 prefix(upTo:) 来获取前缀子字符串:

ini 复制代码
let str = "Hello World"
let index = str.index(str.startIndex, offsetBy: 5)
let prefix = str.prefix(upTo: index)
if prefix == "Hello" {
    print("\(str) 以 Hello 开头")
}

这种方法先利用 index(_:, offsetBy:) 获取前五个字符的下标,然后利用 prefix(upTo:) 函数获取前 5 个字符,最后与 "Hello" 做对比的方式,适用于获取字符串前 n 个字符的情况。

4. 使用字符串区间索引

先获取前 5 个字符的下标,再根据下标区间获取前 5 个字符的值,最后再与对应的字符串对比:

ini 复制代码
let str = "Hello World"
let index = str.index(str.startIndex, offsetBy: 5)
let prefix = str[..<index]
if prefix == "Hello" {
    print("\(str) 以 Hello 开头")
}

5. 使用条件获取

可以使用 prefix(while:) 获取满足条件的前缀:

swift 复制代码
let str = "Hello World"
let prefix = str.prefix { c in
    !c.isWhitespace
}
if prefix == "Hello" {
    print("\(str) 以 Hello 开头")
}

这种方法利用 prefix(while:) 函数获取指定指定条件(第一个空格之前)的字符串,再和 "Hello" 对比得出结果。

6. 使用 firstIndex/lastIndex

可以结合 firstIndex(of:)lastIndex(of:) 获取特定字符的索引,从而获取前缀:

vbscript 复制代码
let str = "Hello World"
if let end = str.firstIndex(of: " "),
   str[..<end] == "Hello" {
    print("\(str) 以 Hello 开头")
}

先用 firstIndex(of:) 方法获取到第一个空格所在的位置,再根据下标区间获取指定的前缀。

7. 使用 prefix(through:) 函数

prefix(through:) 可以获得从开头到指定位置的子集合,跟上边第二种方法差不多,只不过这里的参数传的是下标类型:

ini 复制代码
let str = "Hello World"
let index = str.index(str.startIndex, offsetBy: 4)
let prefix = str.prefix(through: index)
if prefix == "Hello" {
    print("\(str) 以 Hello 开头")
}

以上就是获取字符串前缀的 7 种常用方法,可以根据需要选择最适合的方式。

这里每天分享一个 iOS 的新知识,快来关注我吧

本文同步自微信公众号 "iOS新知",每天准时分享一个新知识,这里只是同步,想要及时学到就来关注我吧!

相关推荐
RollingPin2 小时前
iOS八股文之 多线程
ios·多线程·串行并行·gcd·ios面试·同步异步·nsoperation
AirDroid_cn2 小时前
在 iOS 18 中,控制中心怎样添加应用快捷方式?
macos·ios·cocoa
RollingPin2 小时前
iOS八股文之 内存管理
ios·内存管理·内存泄漏·ios面试·arc·runloop·引用计数
2501_915106328 小时前
iOS 26 APP 性能测试实战攻略:多工具组合辅助方案
android·macos·ios·小程序·uni-app·cocoa·iphone
开开心心loky8 小时前
[iOS] KVC 学习
学习·ios·objective-c·cocoa
00后程序员张17 小时前
iOS混淆与IPA文件加固全流程实战 防止苹果应用被反编译的工程级方案
android·ios·小程序·https·uni-app·iphone·webview
胖虎117 小时前
iOS 推送证书 P8 介绍及生成流程
ios·个推·p8证书·极光推送·ios推送
白熊18818 小时前
【图像大模型】ms-swift 深度解析:一站式多模态大模型微调与部署框架的全流程使用指南
开发语言·ios·swift
2501_9151063218 小时前
iOS 应用加固与苹果软件混淆指南,如何防止 IPA 被反编译与二次打包?
android·ios·小程序·https·uni-app·iphone·webview
用户347475478332818 小时前
把SwiftUI View 转为图片
ios·swiftui