在 Swift 中调整字符串大小

Resize string in Swift

对于通知,我不能超过 256 个字符。我需要将字符串的大小调整为最多 200 个字符。

我怎么能,例如,如果我有一个 210 个字符的字符串,将其大小调整为 197,其余为“...”。但是,如果我有一个 100 个字符的字符串,请不要调整它的大小,因为它适合通知。

谢谢。

我假设您可以在字符串末尾添加省略号。在这种情况下,如果您的字符串超过 200 个字符,则需要从第一个字符(索引:0)到第 197 个字符中提取一个子字符串。然后将“...”连接到该子字符串,并在您的通知中使用它。

我过去使用了另一种可能性:当您生成通知时,您使用 come 算法(我使用普通的老霍夫曼)压缩您的消息并将压缩版本作为有效负载发送。在您的应用程序中,您膨胀压缩消息并显示它,因此实际上超过了大小限制。不用说,只要压缩版本适合通知有效负载,它就可以工作。如果你做不到,你必须事先缩短你的消息——要么用上面描述的方法,然后以纯文本发送,要么你计算出最长的时间,你可以在压缩之前截断你的消息,所以放气后的版本适合有效负载。

我会将此扩展名用于 String。请注意,它并不完全符合您的要求,因为它使用 unicode 省略号字符而不是 3 个句点,但将“...”指定为第二个参数即可:

extension String {
    func ellide(length:Int, ellipsis:String = "…") -> String {
        if characters.count > length {
            return self[startIndex..<startIndex.advancedBy(length - ellipsis.characters.count)] + ellipsis
        } else {
            return self
        }
    }
}
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 ...
*/