Search code examples
stringswiftnotificationsstrip

Resize string in Swift


With notifications I can't exceed more than 256 characters. I need to resize a string to be 200 characters maximum.

How could I, for example if I have an string of 210 characters, resize it to 197 and the rest "...". But if I have one string of 100 characters, don't resize it because it fits in the notification.

Thanks.


Solution

  • let str = "With notifications I can't exceed more than 256 characters. I need to resize a string to be 200 characters maximum. How could I, for example if I have an string of 210 characters, resize it to 197 and the rest \"...\". But if I have one string of 100 characters, don't resize it because it fits in the notification."
    
    func foo(str: String, width: Int)->String {
        let length = str.characters.count
        if length > width {
            let d = length - width + 3
            let n = d < 0 ? 0 : d
            let head = str.characters.dropLast(n)
            return String(head) + "..."
        }
        return str
    }
    
    foo(str, width: 10) // "With no..."
    print(foo(str, width: 200))
    /*
    With notifications I can't exceed more than 256 characters. I need to resize a string to be 200 characters maximum. How could I, for example if I have an string of 210 characters, resize it to 197 ...
    */