Swift5.1语法学习

三、字符串、字符

2019-12-31  本文已影响0人  爱玩游戏的iOS菜鸟

字符串的定义

字符串字面量
  1. 多行字符串字面量里包含了换行,那个换行符(\n)同样会成为字符串里的值,如果不需要换行符在末尾添加(\)
var string = """
abcdefg\
hijklmn
"""

print(string)//输出:abcdefghijklmn 无换行
  1. 多行字符串可以缩进以匹配周围的代码
func function() ->String{
    let string = """
    abcdefg
    hijklmn
        opqrst
    uvw
        xyz
    """
    return string
}
print(function())
/*
输出结果:
abcdefg
hijklmn
 opqrst
uvw
 xyz
 */
字符串中的特殊字符
let sparklingHeart = "\u{1F496}"//💖

【注意】如果需要某些转义字符不生效,需要怎么办呢?

  1. 在字符串字面量中放置扩展分隔符来在字符串中包含特殊字符而不允许生效。将字符串放在双引号( " )内并由#号( # )包裹
  2. 如需要字符串中某个特殊符号生效,使用匹配你包裹的#号数量的#号并在前面写转义符号 \ (数量不同无效当普通字符处理)
let str1 = "Line1\nLine2\nLine3"
let str2 = #"Line1\#nLine2\nLine3"#
let str3 = ##"Line1\#nLine2\##nLine3"##
print(str1,str2,str3,separator: "\n\n", terminator: "\n")
/*输出结果:
Line1
Line2
Line3

Line1
Line2\nLine3

Line1\#nLine2
Line3
 */

字符串相关用法(常用方法)

字符串初始化
var str1 = String.init()
var str2 = String.init("hello,world")
var str6 = String.init("Hello".utf8)
var str3 = String.init(repeating: "hello", count: 3)
var str4 = String()
var str5 = ""
String的增删改查
  1. 查询(查找指定下标 判断是否有值)
var str1 = String.init("hello,world")

print(str1[str1.startIndex])//输出:h
//print(str1[str1.endIndex])//错误:越界
print(str1[str1.index(before: str1.endIndex)])//输出:d
print(str1[str1.index(after: str1.startIndex)])//输出:e

var index:String.Index? = str1.firstIndex(of: "o")//返回可选类型 不确定是否能查到

if let index3 = index {
    let index2 = str1.index(index3, offsetBy: 3)
    print(str1[index3],str1[index2])//输出:o  o
}else{
    print("没有找到")
}

print("\(str1.isEmpty)")//输出:false
print("\(str1.count)")//输出:11
  1. 增加、替换、插入指定范围
//增加字符串
var str1 = String.init("World!")
str1.append("China!")
str1.append(contentsOf: "Wuhan!")
str1 = str1 + "Hongshan!"

print(str1)//输出:World!China!Wuhan!Hongshan!

//插入字符串
var index :String.Index? = str1.firstIndex(of: "H")
str1.insert("😬", at: index!)
str1.insert("😬", at: str1.endIndex)
str1.insert(contentsOf: "HaHa", at: str1.endIndex)
str1.insert(contentsOf: "Hi!", at: str1.index(before: str1.endIndex))
print(str1)//输出:World!China!Wuhan!😬Hongshan!😬HaHHi!a

//区间替换
var str2 = String.init("Wuhan")
var index2 :String.Index? = str2.firstIndex(of: "u")
var index3 :String.Index? = str2.index(before: str2.endIndex)
let replaceSpace = index2!...index3!
str2.replaceSubrange(replaceSpace, with: "德玛西亚")

print(str2)//输出:W德玛西亚

//字符串插值
let value1 = 10,value2 = 20
var str3 = "\(value1)\(value2)"//1020
  1. 删除字符串
var str1 = "abcdefghijklmn"
var index :String.Index = str1.index(before: str1.endIndex)
str1.remove(at: index)//返回值:n 删除成功  str1值: abcdefghijklm
str1.removeFirst()//返回值:a   str1值: bcdefghijklm
str1.removeLast() //返回值:m    str1值: bcdefghijkl

var index2 :String.Index? = str1.firstIndex(of: "d")
str1.removeSubrange(..<index2!)//str1值: defghijkl

let range = str1.index(str1.endIndex, offsetBy: -6)..<str1.endIndex
str1.removeSubrange(range)//str1值: def

str1.removeAll(keepingCapacity: true)//清空 但不释放已分配的空间
str1.removeAll()//清空 默认为false

//删除遍历筛选
var str1 = "asdcbbnn"
str1.removeAll { (char) -> Bool in
    if char > "h"{
        return true
    }else{
        return false
    }
}
print(str1)//输出:adcbb

var str2 = "adcbe7777fg"
str2.removeAll { $0 == "7" }//上面遍历的简写
print(str2)//输出:adcbefg

  1. 更改字符串大小写
str1.uppercased()//ABCDEFGHIJKLMN
str1.lowercased()//abcdefghijklmn
  1. 字符串的比较 、遍历
var str1 = "abCdefghijklmn"
var str2 = "aBcdefghijklmn"
var hasPref :Bool = str1.hasPrefix("abC")//true
var hasSuff :Bool = str2.hasSuffix("lmn")//true
var isEqual :Bool = str1 == str2     //false

for charatar in str1 {
    print(charatar)
}

//使用indices属性访问字符串
for index in str1.indices {
    print(str1[index])
}

String的其他用法
  1. 字符、字符串也能使用区间运算符 但默认不能用在for-in遍历中
let strRange:ClosedRange<String> = "cc"..."ff"
//如果不声明range类型 默认为String
strRange.contains("cb")//输出:false
strRange.contains("cz")//输出:true
strRange.contains("fg")//输出:false

let charRange :Range<Character> = "b"..<"f"
charRange.contains("a")//输出:false
charRange.contains("d")//输出:true
charRange.contains("f")//输出:false
  1. SubString(具体见第二十章 字符串要点)
上一篇 下一篇

猜你喜欢

热点阅读