swift 字符串String的使用方法

时间:2021-10-30 14:34:22

swift 字符串String的使用方法

1、声明

?
1
2
3
4
5
6
7
8
9
10
11
var str = "Hello, playground"
//var str: String = "Hello, playground"
 
 
// 空字符串
let emptyString = ""
let emptyString2 = String()
 
 
// 使用String()初始化字符串
let str2 = String("Hello, swift")

2、判断字符串是否为空

?
1
2
3
// 判断空字符串
str.isEmpty //false
emptyString.isEmpty //true

3、字符串拼接

?
1
2
3
4
5
6
7
8
9
10
11
// String的粘合
let mark = "!!!"
str + mark //Hello, playground!!!
str //Hello, playground
 
 
// 常量String和变量String
str += mark
str //Hello, playground!!!
 
//str2 += mark //let 会报错

4、字符串插值

?
1
2
3
4
5
6
// 字符串插值
let name = "lxy"
let age = 18
let height = 1.78
let s = "My name is \(name), I'm \(age) years old. I'm \(height) meters tall."
print(s) //My name is lxy, I'm 18 years old. I'm 1.78 meters tall.

5、特殊字符

?
1
2
3
4
// 特殊字符
let s = "\\" =>\
let s = "\"" =>"
let s = "\n" =>换行

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/u012903898/article/details/52844130