如何在Swift连接字符串?

在Objective-C中

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

or

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

但我想用swift语言来写。


当前回答

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

例子:

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

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

其他回答

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

      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"

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

希望这对你有所帮助。

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

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

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

你还可以:

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

我相信还有更多的方法。

稍微描述一下

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

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

Note

实际上,let和var与NSString和NSMutableString非常不同,但它有助于类比。

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

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

例子:

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

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

斯威夫特5:

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

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