Разделите строку на две части и узнайте ее элементы - PullRequest
0 голосов
/ 22 апреля 2020

У меня есть строка с URL и текстом! Текст может быть до или после URL. Итак, как я могу разделить строку на две части и узнать, какой из них является текстом, а какой - URL.

Например, строка 1 = "Это переполнение стека { ссылка }" (текст перед URL)

String 2 = "{ ссылка } Это переполнение стека" (текст после URL)

Ответы [ 4 ]

1 голос
/ 22 апреля 2020

Можно попробовать

let str = "This is stack overflow https://stackoverflow.com/questions/ask"
let array = str.components(separatedBy: " ")
let result = array.first { $0.contains("http") }
0 голосов
/ 23 апреля 2020

Попробуйте это (но обработайте пробелы и необязательные):

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

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

if let url = words.first(where: { $0.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://stackoverflow.com/questions/ask"
    print(suffix)   // " and may be some more text."
}
0 голосов
/ 23 апреля 2020

Я нашел решение.

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

let attribute.String1 = NSMutableAttributedString (строка: "(text1) \ n", атрибуты: ноль)

let attribute.String2 = NSMutableAttributedString (строка: "(text2) \ n", атрибуты: ноль)

attribute.String1. 1012 * let originalString = "https://medium.com/@felicity.johnson.mail / how-to-split-a-string-swift-3-0-e9b757445064 проверка нового сообщения"

                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 }
0 голосов
/ 22 апреля 2020

Если в предложении есть пробел между текстом и url , вы можете получить URL следующим образом. :

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

print(stringArray.last)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...