将 String 一分为二并知道其元素

Split String into two and know its elements

我有一个包含 url 和一些文本的字符串!文本可以在 url 之前或 url 之后。那么我怎样才能将字符串一分为二并知道哪个是 Text 哪个是 URL.

例如 String 1 = "This is stack overflow https://whosebug.com/questions/ask"(文本在 url 之前)

String 2 = "https://whosebug.com/questions/ask 这是堆栈溢出"(文本在 url 之后)

你可以试试

let str = "This is stack overflow https://whosebug.com/questions/ask"
let array = str.components(separatedBy: " ")
let result = array.first { [=10=].contains("http") }

如果句子在文本和url之间有space,你可以通过以下方式得到url。 :

let string = "Lorem ipsum dolor sit amet"
let stringArray = string.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

print(stringArray.last)

我找到了解决办法。

func getAttributedText(_ text1:String,text2:String) -> NSAttributedString {

let attributedString1 = NSMutableAttributedString(string:"(text1)\n", attributes: nil)

let attributedString2 = NSMutableAttributedString(string:"(text2)\n", attributes:nil)

attributedString1.append(attributedString2)

return attributedString1 }

let originalString = "https://medium.com/@felicity.johnson.mail/how-to-split-a-string-swift-3-0-e9b757445064 检查新的 post"

                do {
                    let types: NSTextCheckingResult.CheckingType = .link
                    let detector = try? NSDataDetector(types: types.rawValue)
                    let matches = detector?.matches(in: originalString, options: .reportCompletion, range: NSMakeRange(0, originalString.count))
                    var link:String!
                    if (matches != nil){
                        for match in matches! {
                            link = (match.url?.absoluteString)!

                            break;
                        }
                    }
                    let mutableAttributedString = NSMutableAttributedString(string: originalString, attributes: nil)


                    let attributedText = getAttributedText("DOJ watchdog finds no bias in launch of Trump-Russia probe, but uncovers ‘significant’ FBI errors", text2:"The Justice Department’s inspector general, in a long-awaited review concerning the origins of the Russia investigation \n")

                    let userContent : String = ""

           // Get range of text to replace
                    if let range = mutableAttributedString.string.range(of: link){
                        let nsRange = NSRange(range, in: mutableAttributedString.string)

      // Replace content in range with the new content
                        mutableAttributedString.replaceCharacters(in: nsRange, with: userContent)
                    }
          let userTypedContent = mutableAttributedString.string.trimmingCharacters(in: .whitespaces)
                    let urlContent = attributedText.string.trimmingCharacters(in: .whitespaces)
                    UIlablel.text = urlContent + userTypedContent }

试试这个(但要处理空格和可选项):

let sentence =  "This is stack overflow https://whosebug.com/questions/ask and may be some more text."

let words = sentence.components(separatedBy: " ")

if let url = words.first(where: { [=10=].contains("http") }) {

    let splits = sentence.components(separatedBy: url)
    let prefix = splits.first
    let suffix = splits.last

    print(prefix)   // "This is stack overflow "
    print(url)      // "https://whosebug.com/questions/ask"
    print(suffix)   // " and may be some more text."
}