前言:4.0的好多都有改变,但是网上的更新很少.所以呢就随手写一下不多说还是直接上代码
!!!看下面的时候需要注意var和let的区别这里就不详细解释了可以自己去搜一下.
1.定义字符串
func definitionString() -> () {
let name = "小龙"//变量字符串
let m_name = "王"//常量字符串
let m__name = ""//空的字符串
let m___name = String()//空的字符串
print(name,m_name,m__name,m___name);
}
2.字符串拼接
func StringJoint() -> () {
let studentNum = "1"//学生的学号
let studentName = "小龙"//学生的姓名
print(studentNum+studentName)
print("\(studentNum):\(studentName)")
let arr = ["星","期","一"]
//数组转字符串
let today = arr.joined(separator: "__")//将数组中的数据通过__连接
print(today)
///其他类型的转string
let num1 = 10
let num2 = 12
let str1 = "\(num1)+\(num2)"
print(str1)
}
3.枚举字符
func enumChar() -> () {
//遍历
let myStr = "my name is De Shuai Dong 我的"
for char in myStr {
print(char);
}
}
4.获取字符串中指定索引处的字符
func getStrChar() -> () {
let s:String = "SwiftMineStudy"
//取从开始的位置数index等于3的字符
let sub0 = s.index(s.startIndex, offsetBy: 3)
//取从最后的位置数第二个的字符
let sub1 = s.index(s.endIndex, offsetBy: -2)
//从sub0的位置开始数接下来的第二位的字符
let sub2 = s.index(sub0, offsetBy: 2)
//同上
let sub3 = s.index(s.startIndex, offsetBy: 2)
//取sub0之前的一位字符
let sub4 = s.index(before: sub0)
//取sub0之后的一位字符
let sub5 = s.index(after: sub0)
//取sub0之前的左右字符串
let sub6 = s.prefix(upTo: sub0)
//取sub0之后的所有字符串
let sub7 = s.suffix(from: sub0)
//拼接,字符需转为字符串
//lableTest.text = String(s[sub0])+String(s[sub1])+sub6
//反转字符串
//lableTest.text = String(s.reversed())
print(s[sub0],s[sub1],s[sub2],s[sub3],s[sub4],s[sub5],sub6,sub7)
//字符串换行
let name = """
qweqwe
qweqwe
sdfsdfsdf
"""
print(name)
//字符串是否为空
if s.isEmpty {
print("为空")
}else{
print("不为空")
}
//字符串区间截取
//方法一
let snowy = " Let it snow! "
let nsrange = NSRange(location: 3, length: 6)
let start = snowy.index(snowy.startIndex, offsetBy: nsrange.lowerBound)
let end = snowy.index(snowy.startIndex, offsetBy: nsrange.upperBound)
let substringRange = start..
5.字符串的其他用法
func 字符串的其他用法() -> () {
//注意这里是变量
var str:String = "av,1,2,3,4,5,6,7,8,a,b,c,d,e"
//获取字符串长度
print(str.count)
if str.count>3 {
print("长度大了")
}
//去除字符串中的特殊字符 只能去除一个
str.remove(at: str.index(of: ",")!)
print(str)
//字符串转数组
let arr = str.components(separatedBy: ",")
print(arr)
//转大写
let str1 = str.uppercased()
print(str1)
//转小写
let str2 = str.lowercased()
print(str2)
//每个单词首字母大写
let str3 = str.capitalized
print(str3)
//字符串替换
let str4 = str.replacingOccurrences(of: ",", with: "")
print(str4)
//判断是否包含某个字符串
if str.range(of: "av") != nil {
print("包含")
}
if str == str3 {
print("相等")
}else{
print("不相等")
}
//转int
let str5 = "123"
let intNum:Int = Int(str5)!
print(intNum + 3)
}
有用的话点个赞