Swift4 字符串的修改

一、遍历characters,在swift4中characters属性被弃用

  • 之前

let stringA = "Stay Foolish, Stay Hungry"
for character in stringA.characters{
    print(character)
}
  • swift4
let stringA = "Stay Foolish, Stay Hungry"
for character in stringA{
    print(character)
}

二、count

  • 之前
let stringA = "秋水共长天一色"
srtingA.character.count     // 7
  • swift4
let stringA = "秋水共长天一色"     
stringA.count               // 7
stringA.utf8.count          // 21
stringA.utf16.count         // 7

三、substring

关于什么是substring 我来告诉你,点我!

  • 之前
let stringA = "<<>>"
let indexStartOfText = stringA.index(stingA.startIndex, offsetBy:3)
let indexEndOfText = stringA,index(stringA.endIndex, offsetBy:-3)

let subString1 = stringA.substring(from: indexStartOfText) // "Hello>>>"
let subString2 = stringA.substring(to: indexEndOfText) // "<<
let subString3 = stringA.substring(with: indexStartOfText..// "Hello"
  • swift4
let stringA = "<<>>"
let indexStartOfText = stringA.index(stingA.startIndex, offsetBy:3)
let indexEndOfText = stringA,index(stringA.endIndex, offsetBy:-3)

let subString1 = stringA[indexStrtOfText...] // "Hello>>>"
let subString2 = stringA[..EndOfText]  // "<<
let subString3 = stringA[indexStartOfText..EndOfText] // "Hello"
  • swift4使用prefix/suffix方法
let stringA = "0123456789"
let index4 = stringA.index(stringA.startIndex, offsetBy: 4)

// The first of each of these examples is preferred
stringA[...index4]              // "01234"
stringA.prefix(through: index4)

stringA[.."0123"
stringA.prefix(upTo: index4)

stringA[index4...]              // "456789"
stringA.suffix(from: index4)
  • Substring->Sting
let string1 = String(substring1)

四、”“”string”“”控制多行文本输出

let stringA = """
关关雎鸠,
在河之洲,
窈窕淑女,
君子好逑,
"""

也可以控制开头的空格

let stringA = """
    予观夫巴陵胜状,在洞庭一湖。衔远山,吞长江,浩浩汤汤,横无际涯;朝晖夕阴,气象万千。此则岳阳楼之大观也,前人之述备矣。然则北通巫峡,南极潇湘,迁客骚人,多会于此,览物之情,得无异乎?
"""

你可能感兴趣的:(iOS)