从Swift中的字符串中删除某个字符之后的所有字符 [英] Delete all characters after a certain character from a string in Swift
问题描述
我有一个 textField
,我想删除某个字符后的所有字符.
I have a textField
and I would like to remove all character after a certain character.
例如,如果我在 textField 中有单词 Orange
并且我想删除 n
之后的所有字符,我想得到 Ora
删除后.
For instance if what I have in the textField is the word Orange
and I want to remove all characters after the n
I would like to get Ora
after the deletion.
如何在 Swift 中删除字符串中某个字符后的所有字符?
How can I delete all characters after a certain character from a string in Swift?
谢谢
推荐答案
可以使用StringProtocol
方法range(of string:)
,得到结果范围lowerBound,创建一个带有它的 PartialRangeUpTo
并为原始字符串添加下标:
You can use StringProtocol
method range(of string:)
, get the resulting range lowerBound, create a PartialRangeUpTo
with it and subscript the original string:
Swift 4 或更高版本
let word = "orange"
if let index = word.range(of: "n")?.lowerBound {
let substring = word[..<index] // "ora"
// or let substring = word.prefix(upTo: index) // "ora"
// (see picture below) Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collection’s subscript.
// The subscript notation is preferred over prefix(upTo:).
let string = String(substring)
print(string) // "ora"
}
这篇关于从Swift中的字符串中删除某个字符之后的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!