Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get last sentence from String after ". "(Dot And Space)

I am trying to get the last sentence from String after ". "(Dot And Space), Suppose I have a very long string and in that string, there are multiple ". "(Dot And Space) but I want to fetch the String after the very last ". "(Dot And Space) I have tried some of the solutions but I am getting below error

Example String: "Hello. playground!. Hello. World!!! How Are you All?"

Expected Output Needed: "World!!! How Are you All?"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Below is the code which I have tried so far

let fullstring = "Hello. playground!. Hello. World!!! How Are you All?"
let outputString = fullstring.substringAfterLastOccurenceOf(". ") // Here I am getting this error Cannot convert value of type 'String' to expected argument type 'Character'


extension String {
    
    var nsRange: NSRange {
        return Foundation.NSRange(startIndex ..< endIndex, in: self)
    }
    
    subscript(nsRange: NSRange) -> Substring? {
        return Range(nsRange, in: self)
            .flatMap { self[$0] }
    }
    
    func substringAfterLastOccurenceOf(_ char: Character) -> String {
        
        let regex = try! NSRegularExpression(pattern: "\(char)\\s*(\\S[^\(char)]*)$")
        if let match = regex.firstMatch(in: self, range: self.nsRange), let result = self[match.range(at: 1)] {
            return String(result)
        }
        return ""
    }
}

Can anyone help me with this or is there any other way to achieve this?

Thanks in Advance!!

>Solution :

Using components(separatedBy:) instead

let fullstring = "Hello. playground!. Hello. World!!! How Are you All?"
let sliptArr = fullstring.components(separatedBy: ". ")
print(sliptArr[sliptArr.count - 1]) // World!!! How Are you All?
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading