在Swift中提取String中的最后一个单词的方法是什么?因此,如果我有一个Lorem ipsum dolor坐下来,那就回复" amet"。这样做最有效的方法是什么?
答案 0 :(得分:20)
您可以使用String方法enumerateSubstringsInRange。第一个参数只传递字符串Range<Index>
和选项.byWords
。只需将每个子字符串附加到生成的集合中并将其返回。
Swift 5或更高版本(对于较旧的Swift语法检查编辑历史记录)
import Foundation
extension StringProtocol { // for Swift 4 you need to add the constrain `where Index == String.Index`
var byWords: [SubSequence] {
var byWords: [SubSequence] = []
enumerateSubstrings(in: startIndex..., options: .byWords) { _, range, _, _ in
byWords.append(self[range])
}
return byWords
}
}
用法:
let sentence = "Out of this world!!!"
let words = sentence.byWords // ["Out", "of", "this", "world"]
let firstWord = words.first // "Out"
let lastWord = words.last // world"
let first2Words = words.prefix(2) // ["Out", "of"]
let last2Words = words.suffix(2) // ["this", "world"]
没有导入基础
清除过滤字符串的字母和空格的标点字符
let clean = sentence.filter{ $0.isLetter || $0.isWhitespace }
找到字符串中最后一个空格的索引
if let index = clean.lastIndex(of: " ") {
let lastWord = clean[index...]
print(lastWord) // "world"
}
找到字符串中第一个空格的索引
if let index = clean.firstIndex(of: " ") {
let firstWord = clean[...index]
print(firstWord) // "Out""
}
答案 1 :(得分:11)
如果您想要包含基础课程,其他答案都可以。如果你想使用仅限Swift的类,那么你可以这样做:
一种方法是使用索引。这可能是使用长字符串的最快方法:
斯威夫特4:I am a student.<ctrl-z>
或者您可以分割字符串:
斯威夫特4:let str = "Lorem ipsum dolor sit amet"
let size = str.reversed().firstIndex(of: " ") ?? str.count
let startWord = str.index(str.endIndex, offsetBy: -size)
let last = str[startWord...] // -> "amet"
斯威夫特3:
let str = "Lorem ipsum dolor sit amet"
let split = str.split(separator: " ")
let last = String(split.suffix(1).joined(separator: [" "]))
let lastTwo = String(split.suffix(2).joined(separator: [" "]))
print(last) // -> "amet"
print(lastTwo) // -> "sit amet”
斯威夫特2:
let str = "Lorem ipsum dolor sit amet"
let split = str.characters.split(separator: " ")
let last = String(split.suffix(1).joined(separator: [" "]))
let lastTwo = String(split.suffix(2).joined(separator: [" "]))
print(last) // -> "amet"
print(lastTwo) // -> "sit amet”
答案 2 :(得分:8)
我还会考虑使用componentsSeparatedByCharactersInSet
,并使用空白字符集:
let string = "Lorem ipsum dolor sit amet"
let stringArray = string.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
print(stringArray.last)
答案 3 :(得分:4)
首先使用componentsSeparatedByString
按空格将字符串拆分为数组,然后使用.last
var string = "Lorem ipsum dolor sit amet"
var stringArr = string.componentsSeparatedByString(" ")
var lastWord = stringArr.last //amet
答案 4 :(得分:0)
“ @ Leo Dabus”的相同解决方案,但没有切分:(Swift 4.x)
let fullName = "Williams Diaz Robert"
let words = fullName.components(separatedBy: " ")
if(words.count < 2) {
return
}
let fistName = String(words.last ?? "") //Robert
let lastNameArray = words.prefix(words.count - 1) //["Williams","Diaz"]: [String]
let lastName = lastNameArray.joined(separator: " ") // "Williams Diaz"
答案 5 :(得分:0)
雨燕5
extension String {
func trim(_ emptyToNil: Bool = true)->String? {
let text = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return emptyToNil && text.isEmpty ? nil : text
}
var lastWord: String? {
if let size = self.lastIndex(of: " "), size >= self.startIndex {
return String(self[size...]).trim()
}
return nil
}
}
用法
print("Out of this world!!!".lastWord ?? "") // world!!!
答案 6 :(得分:0)
let value = "Hello, I am a String"
let stringArray = value.components(separatedBy: .whitespaces)
let lastWord = stringArray.last ?? ""
print(lastWord)