简体   繁体   English

如何在 Swift 4 中获取具有特定范围的子字符串?

[英]How to get substring with specific ranges in Swift 4?

This is using the example code from the official Swift4 doc这是使用来自官方 Swift4 文档的示例代码

let greeting = "Hi there! It's nice to meet you! 👋"
let endOfSentence = greeting.index(of: "!")!
let firstSentence = greeting[...endOfSentence]
// firstSentence == "Hi there!"

But lets say let greeting = "Hello there world!"但是让我们说let greeting = "Hello there world!" and I want to retrieve only the second word (substring) in this sentence?我只想检索这句话中的第二个单词(子字符串)? So I only want the word "there".所以我只想要“那里”这个词。

I've tried using "world!"我试过使用“世界!” as an argument like let endOfSentence = greeting.index(of: "world!")!作为像let endOfSentence = greeting.index(of: "world!")! but Swift 4 Playground doesn't like that.但 Swift 4 Playground 不喜欢那样。 It's expecting 'Character' and my argument is a string.它期待 'Character' 而我的参数是一个字符串。

So how can I get a substring of a very precise subrange?那么我怎样才能得到一个非常精确的子范围的子字符串呢? Or get nth word in a sentence for greater use in the future?或者在句子中获得第 n 个单词以备将来更多使用?

For swift4, 对于swift4,

let string = "substring test"
let start = String.Index(encodedOffset: 0)
let end = String.Index(encodedOffset: 10)
let substring = String(string[start..<end])

You can search for substrings using range(of:) . 您可以使用range(of:)搜索子字符串。

import Foundation

let greeting = "Hello there world!"

if let endIndex = greeting.range(of: "world!")?.lowerBound {
    print(greeting[..<endIndex])
}

outputs: 输出:

Hello there 

EDIT: 编辑:

If you want to separate out the words, there's a quick-and-dirty way and a good way. 如果你想分开单词,那就是快速而肮脏的方式和好方法。 The quick-and-dirty way: 快速而肮脏的方式:

import Foundation

let greeting = "Hello there world!"

let words = greeting.split(separator: " ")

print(words[1])

And here's the thorough way, which will enumerate all the words in the string no matter how they're separated: 这是彻底的方法,它将枚举字符串中的所有单词,无论它们如何分开:

import Foundation

let greeting = "Hello there world!"

var words: [String] = []

greeting.enumerateSubstrings(in: greeting.startIndex..<greeting.endIndex, options: .byWords) { substring, _, _, _ in
    if let substring = substring {
        words.append(substring)
    }
}

print(words[1])

EDIT 2: And if you're just trying to get the 7th through the 11th character, you can do this: 编辑2:如果你只是想要获得第7个到第11个角色,你可以这样做:

import Foundation

let greeting = "Hello there world!"

let startIndex = greeting.index(greeting.startIndex, offsetBy: 6)
let endIndex = greeting.index(startIndex, offsetBy: 5)

print(greeting[startIndex..<endIndex])

There is one mistake in the first answer. 第一个答案中有一个错误。

Range<String.Index>.upperBound

The upperBound property should be the endIndex For Example: upperBound属性应该是endIndex例如:

let text = "From Here Hello World"
if let result = text.range(of: "Hello World") {
     let startIndex = result.upperBound
     let endIndex = result.lowerBound
     print(String(text[startIndex..<endIndex])) //"Hello World"
}

Old habits die hard. 旧习难改。 I did it the "Java" way and split the string up by spaces, then accessed the second word. 我用“Java”方式做了它并用空格分割了字符串,然后访问了第二个字。

print(greeting.split(separator: " ")[1]) // "there /n"

In Swift 5 encodedOffset (swift 4 func) is deprecated. 在Swift 5中,不推荐使用encodedOffset(swift 4 func)。
You will need to use utf160Offset 您将需要使用utf160Offset

// Swift 5     

let string = "Hi there! It's nice to meet you!"
let startIndex = 10 // random for this example
let endIndex = string.count

let start = String.Index(utf16Offset: startIndex, in: string)
let end = String.Index(utf16Offset: endIndex, in: string)

let substring = String(string[start..<end])

prints -> It's nice to meet you! 打印 - >很高兴见到你!

我使用的最简单的方法是:

String(Array(seed)[2...4])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM