[英]How can I trim this Swift string?
I have a bunch of addresses as strings that are in the following example format: 我有一堆地址作为字符串,格式如下:
8 Smith st, Sydney, New South Wales, Australia 8 Smith st,悉尼,新南威尔士州,澳大利亚
However, I'd like to trim them down to the following format: 但是,我想将它们缩小为以下格式:
8 Smith st, Sydney 悉尼史密斯街8号
How can I acheive this? 我该如何实现? Thanks. 谢谢。
var myString = " Let's trim the whitespace "
var newString = myString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
//Returns "Let's trim the whitespace"
in your Case, first you have to convert it in Array and then convert it as a string as given in below Example 在您的案例中,首先必须将其转换为数组,然后将其转换为字符串,如下面的示例所示
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"]
in your Case, first you have to convert it in Array and then convert it as a string as given in below Example 在您的案例中,首先必须将其转换为数组,然后将其转换为字符串,如下面的示例所示
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
}
Truncate string/text to Specific Length 将字符串/文本截断为特定长度
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 将以下扩展添加到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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.