Swift-字符串:String 的操作

前端之家收集整理的这篇文章主要介绍了Swift-字符串:String 的操作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.判断是否是空值

//判断是否是空值
 let str:String = ""
 if str.isEmpty{
  print("str is nil")
 }
打印结果:str is nil

let str1:String = "hahahaha"
   if str1.isEmpty{
      print("str is nil")
   }else{
       print("str is \( str1)")
   }
   打印结果:str is hahahaha

2.获取字符数量

//获取字符数量
 let str:String = "http://www.baidu.com"
 print("the num is \( str.characters.count)")
 打印结果:the num is 20

3.遍历字符

 //遍历字符
 let str:String = "http://www.baidu.com"
 for charvalue in str.characters{
 print("--->\(charvalue)")
 }
 打印结果:
 --->h --->t --->t --->p --->: --->/ --->/ --->w --->w --->w --->. --->b --->a --->i --->d --->u --->. --->c --->o --->m 

4.字符串是否有特定前缀/后缀

//字符串是否有前后
   let str:String = "http://www.baidu.com"
   if str .hasPrefix("http://"){
       print("hasPrefix--->http://")
   }
   if str .hasSuffix(".com"){
       print("hasSuffix--->.com")
   }

打印结果:
hasPrefix--->http://
hasSuffix--->.com

5.大小写转换

//大小写转换
 let str = "Hello World!"
 //大写
 let uppercase = str.uppercaseString
 //小写
 let lowercase = str.lowercaseString
 //首字母大写
 let capitalized = str.capitalizedString
 print("uppercase--->\(uppercase)")
 print("lowercase--->\(lowercase)")
 print("capitalized--->\(capitalized)")

 打印结果:
 uppercase--->HELLO WORLD!
 lowercase--->hello world!
 capitalized--->Hello World!

6.字符串数组

// 字符串数组
 var strArray = [String]()
 strArray.append("hello")
 strArray.append(" ")
 strArray.append("world!")
 print("strArray--->\(strArray)")
 //拼接字符串
 print("strArray--->\(strArray.joinWithSeparator(""))")
 //拆分字符串
 let newArray = strArray.split("")
 print("strArray--->\(newArray)")

 打印结果:
 strArray--->["hello"," ","world!"]
 strArray--->hello world!
 strArray--->[[ArraySlice(["hello","world!"])]]

7.字符数组删除

//字符数组删除
 var strArray = ["hello","world","!"]
 print("strArray--->\(strArray)")
 //删除第一个
 strArray.removeFirst()
 print("strArray--->\(strArray)")
 //删除最后一个
 strArray.removeLast()
 print("strArray--->\(strArray)")
//删除指定下标的元素
 strArray .removeAtIndex(0)
 print("strArray--->\(strArray)")
//删除所有元素
 strArray .removeAll()
 print("strArray--->\(strArray)")

打印结果:
strArray--->["hello","!"]
strArray--->[" ","world"]
strArray--->["world"]
strArray--->[]
原文链接:https://www.f2er.com/swift/324329.html

猜你在找的Swift相关文章