Jak połączyć struny w języku Swift?

Jak połączyć string w Swift?

W {[2] } lubimy

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

Lub

NSString *resultStr=[NSString stringWithFormat:@"%@ is a new Programming Language",string];
Ale chcę to zrobić w szybkim języku.
Author: idmean, 2014-06-04

20 answers

Można łączyć łańcuchy na wiele sposobów:

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

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

Można też zrobić:

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

Jestem pewien, że jest więcej sposobów.

Bit opisu

let tworzy stałą. (coś w rodzaju NSString). Nie można zmienić jego wartości po jej ustawieniu. Nadal możesz dodawać go do innych rzeczy i tworzyć nowe zmienne.

var tworzy zmienną. (coś w rodzaju NSMutableString), więc możesz zmienić jego wartość. Ale na to już odpowiedziano kilka razy na przepełnienie stosu, (patrz różnica między let i var).

Uwaga

W rzeczywistości let i var bardzo różne od NSString i NSMutableString, ale pomaga to w analogii.

 343
Author: Fogmeister,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:41

Możesz dodać ciąg znaków w następujący sposób:

  • str += ""
  • str = str + ""
  • str = str + str2
  • str = "" + ""
  • str = "\(variable)"
  • str = str + "\(variable)"
Chyba nazwałem je wszystkie.
 64
Author: Arbitur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-04 10:02:35
var language = "Swift" 
var resultStr = "\(language) is a new programming language"
 33
Author: yoeriboven,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-04 15:53:02

To też zadziała:

var string = "swift"
var resultStr = string + " is a new Programming Language"
 13
Author: CW0007007,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-15 08:21:47

\ to jest używane do dodawania jednego łańcucha do drugiego.

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

Możesz spróbować również: - + słowo kluczowe.

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

Spróbuj tego kodu.

 11
Author: Jitendra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-05 13:27:06
let the_string = "Swift"
let resultString = "\(the_string) is a new Programming Language"
 10
Author: Bagvendt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-04 12:26:54

Bardzo Proste:

let StringA = "Hello"
let StringB = "World"
let ResultString = "\(StringA)\(StringB)"
println("Concatenated result = \(ResultString)")
 9
Author: Rajesh Loganathan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-04 10:24:45

Możesz teraz użyć stringByAppendingString w języku Swift.

var string = "Swift"
var resultString = string.stringByAppendingString(" is new Programming Language")
 9
Author: Mark Moeykens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-18 05:47:57

Xcode nie zaakceptowało opcjonalnych ciągów dodanych normalnym ciągiem. Napisałem to rozszerzenie, aby rozwiązać ten problem:

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

Wtedy możesz nazwać to tak:

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

Jednak teraz można też zrobić coś takiego:

var str1: String?
var str1 = "hi"
var str2 = " my name is"
str1! += str2
 5
Author: Esqarrouth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-04 15:54:22

Nazywa się to interpolacją łańcuchową. Jest to sposób tworzenia nowego ciągu ze stałymi, zmiennymi, literałami i wyrażeniami. dla przykładu:

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

Również

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"

Oznacza również jako łączące wartości łańcuchowe.

Mam nadzieję, że to ci pomoże.
 4
Author: Anil Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-23 18:48:33

Aby wydrukować połączony ciąg za pomocą

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

Lub String3 przechowuje wyjście kombinacji 2 ciągów

let strin3 = "\(string1)\(string2)"
 3
Author: Pvni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-10 12:51:55

Można również użyć stringByAppendingFormat w języku Swift.

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
 3
Author: Pushpa Y,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-27 06:11:56

Swift 4.2

Możesz również użyć rozszerzenia:

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

Zastosowanie:

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

Wynik:

"The Man"
"The"
"Man"
 2
Author: Nik Kov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55

[[4]}From: Matt Neuburg Book " iOS 13 Podstawy programowania za pomocą Swift." :

Aby połączyć (konkatenować) dwa ciągi, najprostszym podejściem jest użycie + operatora:

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

Ta wygodna notacja jest możliwa, ponieważ operator + jest przeciążony: robi jedną rzecz, gdy operandami są liczby (dodawanie liczb), a drugą, gdy operandami są łańcuchy (konkatenacja). Operatorem + jest + = przypisanie Skrót; oczywiście zmienna po lewej stronie musi być zadeklarowana za pomocą var:

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

Jako alternatywa do +=, możesz wywołać metodę instancji append (_:) :

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

Innym sposobem łączenia łańcuchów {[8] } jest metoda joined(separator:) . Rozpoczynasz od tablicy łańcuchów do konkatenacji i przekazujesz jej łańcuch, który ma być wstawiony między nimi wszystkimi:

let s = "hello"
let s2 = "world"
let space = " "
let greeting = [s,s2].joined(separator:space)
 2
Author: H S Progr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-18 14:37:19

You could use SwiftString ( https://github.com/amayne/SwiftString ) aby to zrobić.

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

Zastrzeżenie: napisałem to rozszerzenie

 1
Author: eurobrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-06 17:25:28

Właśnie przełączyłem się z Objective-C na Swift (4) i stwierdzam, że często używam:

let allWords = String(format:"%@ %@ %@",message.body!, message.subject!, message.senderName!)
 1
Author: Sjakelien,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-04 13:00:05

Swift 5

Można to osiągnąć za pomocą appending API. Zwraca nowy ciąg znaków utworzony przez dołączenie danego ciągu do odbiornika.

Szczegóły API: tutaj

Użycie :

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

Wynik :

Hello
Hello Namaste
 1
Author: Vittal Pai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-08 11:48:31

W Swift 5 apple wprowadza surowe ciągi znaków używając # symbols.

Przykład:

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

Symbol # jest konieczny po \. Zwykły \(name)będzie interpretowany jako znaki w łańcuchu.

 0
Author: Yogendra Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-21 09:39:38

Kilka słów o wydajności

Pakiet testowy interfejsu użytkownika na iPhone 7 (prawdziwe urządzenie) z iOS 14]}
var result = ""
for i in 0...count {
    <concat_operation>
}

Count = 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

Wyłącz następne testy:

  • Plus do 100_000 ~10s
  • interpolacja do 100_000 ~10S
  • NSString do 10_000 - > problemy z pamięcią

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

* Uwaga o Konwertuj Int na String

Kod źródłowy

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

}

 0
Author: yoAlex5,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-14 23:01:19

Konkatenacja odnosi się do łączenia łańcuchów w języku Swift. Ciągi mogą zawierać teksty, liczby całkowite, a nawet emotikony! Istnieje wiele sposobów łączenia łańcuchów. Wymieńmy kilka:

Ten Sam Ciąg

Za pomocą +=

Jest to przydatne, jeśli chcemy dodać do już istniejącego ciągu znaków. Aby to zadziałało, nasz łańcuch powinien być zmienny lub może być modyfikowany, deklarując go jako zmienną. Na przykład:

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

różne Struny

Jeśli chcemy łączyć ze sobą różne ciągi, na przykład:

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

Możemy użyć dowolnego z następujących:

1) Użycie +

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

Zauważ, że każdy łańcuch może być zmienną lub stałą. Zadeklaruj ją jako stałą, jeśli zmienisz wartość tylko raz.

2) String Interpolation

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

3) Dodawanie

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

Odnoszą się do ciągów i znaków zSwift Book dla więcej.

Aktualizacja: testowany na Swift 5.1

 0
Author: mjoe7,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-16 20:24:46