簡體   English   中英

如何修剪此Swift字符串?

[英]How can I trim this Swift string?

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

8 Smith st,悉尼,新南威爾士州,澳大利亞

但是,我想將它們縮小為以下格式:

悉尼史密斯街8號

我該如何實現? 謝謝。

在這里您可以使用此功能修剪空白

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"]

要了解更多,您可以從這里學習

在您的案例中,首先必須將其轉換為數組,然后將其轉換為字符串,如下面的示例所示

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
}

將字符串/文本截斷為特定長度

如果您輸入了句子/文本塊,並且您只想在文本中保存指定的長度。 將以下擴展添加到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
    }
  }
}

采用

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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM