swift初探03 字符串操做

字符串操做

01 获取长度

var a = "he l lo"
print(a.count) // 计算空格,输出7

02 String.Index类型

String.Index类型表示字符串内某一个字符的位置。swift

能够利用a[String.Index]来获取某一个位置的字符。app

var a = "hello"
print(a.startIndex) // 输出Index(_rawBits: 1)
print(a[a.startIndex]) // 获取字符串第一位,输出h
  • 如何输出最后一位呢?code

    print(a[a.endIndex]) // 报错,由于endIndex的位置是字符串的结束符,并非看到的最后一个字符ci

    能够用a.index(before: String.Index)a.index(after: String.Index)分别获取某一个位置的前一位和后一位。rem

    a[a.index(before: a.endIndex)]就能够获取到字符串最后一个字符。字符串

  • 如何输出指定的某一位?string

    a[a.index(a.startIndex, offsetBy: 2)],意为:从a.startIndex开始,日后数两位。it

    若是offsetBy后面使用了一个负数,那么就是从后往前数。io

  • 输出某一段的字符for循环

    var begin = a.index(a.startIndex, offsetBy: 1)
    var end = a.index(a.startIndex, offsetBy:4)
    print(str[begin...end]) // 输出ello

    或者使用prefix(Int)方法来获取前n个字符:

    var str = a.prefix(2)
    print(str) // 输出he
  • 如何找到第一次出现某字符的位置

    a.firstIndex(of: "e")

03 增删改查

1. 查

  • 判断字符是否在字符串中

    使用contains(Char)方法:(大小写敏感)

    var str = "hello"
    print(str.contains("h")) // true
    print(str.contains("hel")) // true

    也能够使用contains(where: String.contains(""))方法:(这种方法只要有一个包含就返回真值)

    var str = "hello"
    print(str.contains(where: String.contains("ae"))) // true
  • 判断字符串的开头或结尾是不是某字符

    可以使用hasPrefix("")判断开头

    var str = "hello"
    print(str.hasPrefix("h")) // true
    print(str.hasPrefix("he")) // true
    print(str.hasPrefix("e")) // false

    使用hasSuffix()判断结尾

    var str = "hello"
    print(str.hasPrefix("o")) // true
    print(str.hasPrefix("lo")) // true
    print(str.hasPrefix("ol")) // false

2. 增

  • 字符串结尾增长新字符串

    append()便可:

    var str = "hello"
    str.append(" world") // hello world
  • 在某个位置增长某段字符串

    insert(contentsOf: str, at: String.Index)能够在at位置的前面插入str:

    var str = "hello"
    str.insert(contentsOf: "AAA", at: str.startIndex) // 	AAAhello

3. 改

  • 替换某一字段

    replaceSubrange(section, with: "lalala") section是String.Index的区间范围,替换为"lalala":

    var str = "hello"
    let section = str.startIndex...str.index(str.endIndex, offsetBy: -2)
    str.replaceSubrange(section, with: "lalala") // "lalalao"

    也能够使用replacingOccurrences(of: str, with: "jj")将str字段替换为"jj":

    var str = "hello"
    str.replacingOccurrences(of: "ll", with: "jj") // "hejjo"

    若是没有该字段,则不替换

4. 删

  • 删除某位置的字符

    remove(at: String.Index)

    var str = "hello"
    str.remove(at: str.index(str.startIndex, offsetBy: 2)) // l
    print(str) // helo
  • 删除某字段

    removeSubrange(String.Index...String.Index)

    var str = "hello"
    str.removeSubrange(str.startIndex...str.index(str.endIndex, offsetBy: -2))
    print(str) // o

04 利用for循环遍历字符串

  • 直接遍历

    var str = "hello"
    for item in str {
      print(item)
    }
  • 使用index()方法来遍历

    var str = "hello"
    for item in 0..<str.count {
        print(str[str.index(str.startIndex, offsetBy: item)])
    }
相关文章
相关标签/搜索