我怎样才能 trim 这个 Swift 字符串?

How can I trim this Swift string?

我有一堆地址作为字符串,格式如下:

8 Smith st, Sydney, New South Wales, Australia

不过,我想 trim 将它们缩减为以下格式:

悉尼史密斯街 8 号

我怎样才能做到这一点?谢谢

在这里你可以trim白色space使用这个

var myString = "    Let's trim the whitespace    "
var newString = myString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
//Returns "Let's trim the whitespace"

在您的案例中,首先您必须将其转换为数组,然后将其转换为字符串,如下面的示例

var myString = "Berlin, Paris, New York, San Francisco"
var myArray = myString.componentsSeparatedByString(",")
//Returns an array with the following values:  ["Berlin", " Paris", " New York", " San Francisco"]

For More you can learn From here

在您的案例中,首先您必须将其转换为数组,然后将其转换为字符串,如下面的示例

var myString = "8 Smith st, Sydney, New South Wales, Australia"
var myArray = myString.componentsSeparatedByString(",")
//Returns an array with the following values:  ["8 Smith st", " Sydney", " New South Wales", " Australia"]

if myArray.count > 1
{
    println(myArray[0]) //8 Smith st
    println(myArray[1]) //Sydney
}

将 string/text 截断为特定长度

If you have entered block of sentence/text and you want to save only specified length out of it text. Add the following extension to Class

extension String {

   func trunc(_ length: Int) -> String {
    if self.characters.count > length {
        return self.substring(to: self.characters.index(self.startIndex, offsetBy: length))
    } else {
        return self
    }
  }
}

Use

var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
//str is length 74
print(str)
//O/P:  Lorem Ipsum is simply dummy text of the printing and typesetting industry.

str = str.trunc(40)
print(str)
//O/P: Lorem Ipsum is simply dummy text of the