我如何在Swift连接字符串?

如何在Swift连接字符串?

Objective-C中,我们喜欢

NSString *string = @"Swift";
NSString *resultStr = [string stringByAppendingString:@" is a new Programming Language"];

NSString *resultStr=[NSString stringWithFormat:@"%@ is a new Programming Language",string];

但我想用swift语言来写。

325403 次浏览
var language = "Swift"
var resultStr = "\(language) is a new programming language"

这也会起作用:

var string = "swift"
var resultStr = string + " is a new Programming Language"
let the_string = "Swift"
let resultString = "\(the_string) is a new Programming Language"

你可以用多种方式连接字符串:

let a = "Hello"
let b = "World"


let first = a + ", " + b
let second = "\(a), \(b)"

你还可以:

var c = "Hello"
c += ", World"

我相信还有更多的方法。

稍微描述一下

let创建一个常量。(有点像NSString)。一旦你设置了它,你就不能改变它的值。你仍然可以把它添加到其他东西,并创建新的变量。

var创建一个变量。(有点像NSMutableString),所以你可以改变它的值。但是这个问题已经在Stack Overflow上被回答了几次(参见之间的差异let和var)。

请注意

实际上,letvarNSStringNSMutableString中的非常不同的,但这有助于类比。

你可以通过以下方式添加字符串:

  • str += ""
  • str = str + ""
  • str = str + str2
  • str = "" + ""
  • str = "\(variable)"
  • str = str + "\(variable)"

我想我把它们都叫出来了。

\ this被用来将一个字符串附加到另一个字符串。

var first = "Hi"
var combineStr = "\(first) Start develop app for swift"

你也可以试试这个:- +关键字。

 var first = "Hi"
var combineStr = "+(first) Start develop app for swift"

试试这段代码。

来打印组合字符串

Println("\(string1)\(string2)")

或String3存储2个字符串组合的输出

let strin3 = "\(string1)\(string2)"

非常简单:

let StringA = "Hello"
let StringB = "World"
let ResultString = "\(StringA)\(StringB)"
println("Concatenated result = \(ResultString)")

Xcode不接受与普通字符串一起添加的可选字符串。我写了这个扩展来解决这个问题:

extension String {
mutating func addString(str: String) {
self = self + str
}
}

然后你可以这样称呼它:

var str1: String?
var str1 = "hi"
var str2 = " my name is"
str1.addString(str2)
println(str1) //hi my name is

然而,你现在也可以这样做:

var str1: String?
var str1 = "hi"
var str2 = " my name is"
str1! += str2

你可以使用SwiftString (https://github.com/amayne/SwiftString)来做到这一点。

"".join(["string1", "string2", "string3"]) // "string1string2string"
" ".join(["hello", "world"]) // "hello world"

免责声明:我写了这个扩展

你也可以在Swift中使用stringByAppendingFormat。

var finalString : NSString = NSString(string: "Hello")
finalString = finalString.stringByAppendingFormat("%@", " World")
print(finalString) //Output:- Hello World
finalString = finalString.stringByAppendingFormat("%@", " Of People")
print(finalString) //Output:- Hello World Of People

你现在可以在Swift中使用stringByAppendingString

var string = "Swift"
var resultString = string.stringByAppendingString(" is new Programming Language")

它被称为字符串插值。 它是用常量,变量,字面量和表达式创建新字符串的方法。 例如:< / p >

      let price = 3
let staringValue = "The price of \(price) mangoes is equal to \(price*price) "

let string1 = "anil"
let string2 = "gupta"
let fullName = string1 + string2  // fullName is equal to "anilgupta"
or
let fullName = "\(string1)\(string2)" // fullName is equal to "anilgupta"

它也意味着串联字符串值。

希望这对你有所帮助。

我刚从Objective-C切换到Swift(4),我发现我经常使用:

let allWords = String(format:"%@ %@ %@",message.body!, message.subject!, message.senderName!)

斯威夫特4.2

你也可以使用扩展:

extension Array where Element == String? {
func compactConcate(separator: String) -> String {
return self.compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: separator)
}
}

使用:

label.text = [m.firstName, m.lastName].compactConcate(separator: " ")

结果:

"The Man"
"The"
"Man"

在Swift 5中,apple引入了使用#符号的原始字符串。

例子:

print(#"My name is "XXX" and I'm "28"."#)
let name = "XXX"
print(#"My name is \#(name)."#)

符号#必须在\后面。常规的\(name)将被解释为字符串中的字符。

来自:Matt Neuburg书“iOS 13编程基础与Swift。”:

要获得结合(连接)两个字符串,简单的方法是使用+操作符:

let s = "hello"
let s2 = " world"
let greeting = s + s2
这种方便的表示法是可能的,因为+操作符是重载的:当操作数是数字(数字加法)时它做一件事,当操作数是字符串(连接)时它做另一件事。 +操作符带有一个+ =赋值快捷键;当然,左边的变量必须声明为var:

var s = "hello"
let s2 = " world"
s += s2

作为替代+ =的实例方法,你可以调用追加(_:)实例方法:

var s = "hello"
let s2 = " world"
s.append(s2)

另一种连接字符串的方法加入(分隔符:)方法。你从一个要连接的字符串数组开始,并将插入它们之间的字符串交给它:

let s = "hello"
let s2 = "world"
let space = " "
let greeting = [s,s2].joined(separator:space)

斯威夫特5

你可以使用appending API来实现。这将返回一个通过将给定字符串追加到接收器而生成的新字符串。

API详细信息:在这里

使用:

var text = "Hello"
text = text.appending(" Namaste")

结果:

Hello
Hello Namaste

快速连接字符串

关于性能的几句话

UI测试包在iPhone 7(真实设备)与iOS 14

var result = ""
for i in 0...count {
<concat_operation>
}


计数= 5_000

//Append
result.append(String(i))                         //0.007s 39.322kB


//Plus Equal
result += String(i)                              //0.006s 19.661kB


//Plus
result = result + String(i)                      //0.130s 36.045kB


//Interpolation
result = "\(result)\(i)"                         //0.164s 16.384kB


//NSString
result = NSString(format: "%@%i", result, i)     //0.354s 108.142kB


//NSMutableString
result.append(String(i))                         //0.008s 19.661kB

禁用下一个测试:

  • 加上高达100_000 ~10s
  • 插补可达100_000 ~10s
  • NSString to 10_000 ->内存问题

Count = 1_000_000

//Append
result.append(String(i))                         //0.566s 5894.979kB


//Plus Equal
result += String(i)                              //0.570s 5894.979kB


//NSMutableString
result.append(String(i))                         //0.751s 5891.694kB

*注意将Int转换为字符串

源代码

import XCTest


class StringTests: XCTestCase {
let count = 1_000_000
    

let metrics: [XCTMetric] = [
XCTClockMetric(),
XCTMemoryMetric()
]
    

let measureOptions = XCTMeasureOptions.default
    

override func setUp() {
measureOptions.iterationCount = 5
}
    

func testAppend() {
var result = ""
measure(metrics: metrics, options: measureOptions) {
for i in 0...count {
result.append(String(i))
}
}
}
    

func testPlusEqual() {
var result = ""
measure(metrics: metrics, options: measureOptions) {
for i in 0...count {
result += String(i)
}
}
}
    

func testPlus() {
var result = ""
measure(metrics: metrics, options: measureOptions) {
for i in 0...count {
result = result + String(i)
}
}
}
    

func testInterpolation() {
var result = ""
measure(metrics: metrics, options: measureOptions) {
for i in 0...count {
result = "\(result)\(i)"
}
}
}
    

//Up to 10_000
func testNSString() {
var result: NSString =  ""
measure(metrics: metrics, options: measureOptions) {
for i in 0...count {
result = NSString(format: "%@%i", result, i)
}
}
}
    

func testNSMutableString() {
let result = NSMutableString()
measure(metrics: metrics, options: measureOptions) {
for i in 0...count {
result.append(String(i))
}
}
}
}


串联是指Swift中字符串的组合。字符串可能包含文本,整数,甚至表情符号!字符串连接有很多方法。让我列举一些:

< >强相同字符串< / >强

使用+ =

如果我们想要添加到一个已经存在的String,这是很有用的。为此,我们的String应该是可变的或可以修改的,因此将其声明为变量。例如:

var myClassmates = "John, Jane"
myClassmates += ", Mark" // add a new Classmate
// Result: "John, Jane, Mark"

< >强不同的字符串< / >强

如果我们想把不同的字符串组合在一起,例如:

let oldClassmates = "John, Jane"
let newClassmate = "Mark"

我们可以使用以下任何一种:

1)使用+

let myClassmates = oldClassmates + ", " + newClassmate
// Result: "John, Jane, Mark"

注意,每个字符串可以是一个变量或常量。如果你只改变一次值,就把它声明为常量。

2)字符串插值

let myClassmates = "\(oldClassmates), \(newClassmate)"
// Result: "John, Jane, Mark"

3)添加

let myClassmates = oldClassmates.appending(newClassmate)
// Result: "John, Jane, Mark"

参考Strings &斯威夫特的书中的字符。

更新:在Swift 5.1上测试

斯威夫特5:

数组的字符串变成一个单一的字符串

let array = ["Ramana","Meharshi","Awareness","Oneness","Enlightnment","Nothing"]
let joined = array.joined(separator: ",")