简体   繁体   English

如何在 Swift 中连接字符串?

[英]How do I concatenate strings in Swift?

How to concatenate string in Swift?如何在 Swift 中连接字符串?

In Objective-C we do likeObjective-C我们确实喜欢

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

or或者

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

But I want to do this in Swift-language.但我想用 Swift 语言来做这件事。

You can concatenate strings a number of ways:您可以通过多种方式连接字符串:

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

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

You could also do:你也可以这样做:

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

I'm sure there are more ways too.我相信还有更多的方法。

Bit of description一点描述

let creates a constant. let创建一个常量。 (sort of like an NSString ). (有点像NSString )。 You can't change its value once you have set it.一旦你设置了它,你就不能改变它的值。 You can still add it to other things and create new variables though.您仍然可以将其添加到其他内容并创建新变量。

var creates a variable. var创建一个变量。 (sort of like NSMutableString ) so you can change the value of it. (有点像NSMutableString )所以你可以改变它的值。 But this has been answered several times on Stack Overflow, (see difference between let and var ).但这已在 Stack Overflow 上多次回答,(参见let 和 var 之间的区别)。

Note笔记

In reality let and var are very different from NSString and NSMutableString but it helps the analogy.实际上letvarNSStringNSMutableString非常不同,但它有助于类比。

You can add a string in these ways:您可以通过以下方式添加字符串:

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

I think I named them all.我想我给他们起了名字。

var language = "Swift" 
var resultStr = "\(language) is a new programming language"

This will work too:这也将起作用:

var string = "swift"
var resultStr = string + " is a new Programming Language"

\\ this is being used to append one string to another string. \\ 这用于将一个字符串附加到另一个字符串。

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

You can try this also:- + keyword.你也可以试试这个:- + 关键字。

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

Try this code.试试这个代码。

let the_string = "Swift"
let resultString = "\(the_string) is a new Programming Language"

Very Simple:很简单:

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

You can now use stringByAppendingString in Swift.您现在可以在 Swift 中使用stringByAppendingString

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

Xcode didn't accept optional strings added with a normal string. Xcode 不接受使用普通字符串添加的可选字符串。 I wrote this extensions to solve that problem:我写了这个扩展来解决这个问题:

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

Then you can call it like:然后你可以这样称呼它:

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

However you could now also do something like this:但是,您现在也可以执行以下操作:

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

It is called as String Interpolation.它被称为字符串插值。 It is way of creating NEW string with CONSTANTS, VARIABLE, LITERALS and EXPRESSIONS.它是用常量、变量、文字和表达式创建新字符串的方法。 for examples:举些例子:

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

also

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"

it also mean as concatenating string values.它也意味着连接字符串值。

Hope this helps you.希望这对你有帮助。

To print the combined string using使用打印组合字符串

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

or String3 stores the output of combination of 2 strings或 String3 存储 2 个字符串组合的输出

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

One can also use stringByAppendingFormat in Swift.还可以在 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 4.2斯威夫特 4.2

You can also use an extension:您还可以使用扩展名:

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

Use:用:

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

Result:结果:

"The Man"
"The"
"Man"

From: Matt Neuburg Book “iOS 13 Programming Fundamentals with Swift.”来自:Matt Neuburg 书籍“iOS 13 编程基础与 Swift”。 :

To combine (concatenate) two strings, the simplest approach is to use the + operator :组合(连接)两个字符串,最简单的方法是使用+ 运算符

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

This convenient notation is possible because the + operator is overloaded: it does one thing when the operands are numbers (numeric addition) and another when the operands are strings (concatenation).这种方便的表示法是可能的,因为+ 运算符是重载的:当操作数是数字时它做一件事(数字加法),而当操作数是字符串时它做另一件事(连接)。 The + operator comes with a += assignment shortcut; + 运算符带有+= 赋值快捷方式; naturally, the variable on the left side must have been declared with var:自然,左边的变量肯定是用 var 声明的:

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

As an alternative to += , you can call the append(_:) instance method:作为+=替代方法,您可以调用append(_:)实例方法:

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

Another way of concatenating strings is with the joined(separator:) method.另一种连接字符串的方法是使用joined(separator:)方法。 You start with an array of strings to be concatenated, and hand it the string that is to be inserted between all of them:您从要连接的字符串数组开始,并将要插入到所有字符串之间的字符串交给它:

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

Swift 5斯威夫特 5

You can achieve it using appending API.您可以使用appending API 来实现它。 This returns a new string made by appending a given string to the receiver.这将返回通过将给定字符串附加到接收器而制成的新字符串。

API Details : here API 详细信息: 这里

Use :使用

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

Result :结果

Hello
Hello Namaste

You could use SwiftString ( https://github.com/amayne/SwiftString ) to do this.您可以使用 SwiftString ( https://github.com/amayne/SwiftString ) 来执行此操作。

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

DISCLAIMER: I wrote this extension免责声明:我写了这个扩展

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

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

Several words about performance关于性能的几个词

UI Testing Bundle on iPhone 7(real device) with iOS 14带有 iOS 14 的 iPhone 7(真实设备)上的 UI 测试包

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

Count = 5_000计数 = 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

Disable next tests:禁用下一个测试:

  • Plus up to 100_000 ~10s加上高达 100_000 ~10s
  • interpolation up to 100_000 ~10s插值高达 100_000 ~10s
  • NSString up to 10_000 -> memory issues NSString最多 10_000 -> 内存问题

Count = 1_000_000计数 = 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

*Note about Convert Int to String *关于将 Int 转换为 String 的注意事项

Source code源代码

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))
            }
        }
    }

}

Concatenation refers to the combining of Strings in Swift.连接指的是 Swift 中字符串的组合。 Strings may contain texts, integers, or even emojis!字符串可能包含文本、整数,甚至表情符号! There are many ways to String Concatenation.字符串连接的方法有很多。 Let me enumerate some:让我列举一些:

Same String相同的字符串

Using +=使用 +=

This is useful if we want to add to an already existing String.如果我们想添加到已经存在的字符串,这很有用。 For this to work, our String should be mutable or can be modified, thus declaring it as a Variable.为此,我们的 String 应该是可变的或可以修改的,因此将其声明为变量。 For instance:例如:

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

Different Strings不同的字符串

If we want to combine different Strings together, for instance:如果我们想将不同的字符串组合在一起,例如:

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

We can use any of the following:我们可以使用以下任何一种:

1) Using + 1) 使用 +

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

Notice that the each String may be a Variable or a Constant.请注意,每个字符串可能是变量或常量。 Declare it as a Constant if you're only gonna change the value once.如果您只想更改一次值,请将其声明为常量。

2) String Interpolation 2) 字符串插值

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

3) Appending 3) 附加

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

Refer to Strings & Characters from the Swift Book for more.有关更多信息,请参阅Swift Book 中的Strings & Characters。

Update: Tested on Swift 5.1更新:在 Swift 5.1 上测试

In Swift 5 apple has introduces Raw Strings using # symbols.在 Swift 5 中,苹果使用 # 符号引入了原始字符串。

Example:例子:

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

symbol # is necessary after \\. \\ 后必须有符号#。 A regular \\(name) will be interpreted as characters in the string.常规 \\(name) 将被解释为字符串中的字符。

Swift 5:斯威夫特 5:

Array of strings into a single string将字符串数组转换为单个字符串

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM