当前位置: 首页>编程语言>正文

swift5处理子字符串 swift 字符串长度

let someString = "Some string literal Value"

字符串字面两包括以下特殊字符:
1.转义特殊字符 \0 (空字符)、\(反斜线)、\t (水平制表符)、\n (换行符)、\r (回车符)、\” (双引号)、\’ (单引号)。
2.单字节 Unicode 标量,写成 \xnn,其中 nn 为两位十六进制数。
3.双字节 Unicode 标量,写成 \unnnn,其中 nnnn 为四位十六进制数。
4.四字节 Unicode 标量,写成 \Unnnnnnnn,其中 nnnnnnnn 为八位十六进制数

let wiseWords = "\"Imageination is more important than knowledge\"-Einstein"
//""Imageination is more important than knowledge"-Einstein"

let dollarSign = "\u{24}"   // $,  Unicode scalar U+0024
let blackHeart = "\u{2665}" // ♥,  Unicode scalar U+2665
let sparklingHeart = "\u{1F496}"    // ��, Unicode scalar U+1F496

初始化空字符串

var emptyString = ""
var anotherEmptyString = String()

通过检查 Boolean 类型的 isEmpty 属性来判断该字符串是否为空

if emptyString.isEmpty {
    print("Nothing to see here")
}
// Prints "Nothing to see here"

使用字符(Characters)

for character in "Dog!��".characters {
    print(character)
}
// D
// o
// g
// !
// ��
  • 字符串可变性
  • 通过将一个特定字符串分配给一个变量(对其进行修改)或者常量(保证其不会被修改)来指定该字符串是否可以被修
var variableString = "Horse"
variableString += "add carriage"

for-in 循环在 For Loops 中

let exclamationMark: Character = "!"

let catCharacters: [Character] = ["C", "a", "t", "!", "��"]
let catString = String(catCharacters)
print(catString)
// Prints "Cat!��"

//连接字符串和字符: 通过加法运算符 (+) 
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// prints: "hello there"

//也可以通过加法赋值运算符 (+=) 
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"

//使用 append()方法
 welcome.append(exclamationMark)
// welcome now equals "hello there!"

使用字符(Characters),利用for-in循环来遍历字符串的每一个字符

for char in "dog".characters {
    print(char)
}

字符串插值

let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"

字符串长度

let unusualMenagerie = "Koala ��, Snail ��, Penguin ��, Dromedary ��"
print("unusualMenagerie has \(unusualMenagerie.characters.count) characters")
// Prints "unusualMenagerie has 40 characters"


var word = "cafe"
print("the number of characters in \(word) is \(word.characters.count)")
// Prints "the number of characters in cafe is 4"

word += "\u{301}"    // COMBINING ACUTE ACCENT, U+0301

print("the number of characters in \(word) is \(word.characters.count)")
// Prints "the number of characters in café is 4"

*访问和修改字符串
*可以通过其方法和属性,或者下标,来访问或者修改字符串
*字符串索引swift的字符串具有相关联的索引类型(String.Index),可对应其没个位置的Character
*startIndex:访问String第一个位置的字符 endIndex: 访问String最后一个位置的字符(一个空的字符串或者长度为1的字符串,startIndex和endIndex相等)
*predecessor(), successor(), advancedBy()一个String.Index值可以通过调用predecessor()方法来访问其前一个index, 调用successor()来访问其后一个index, 或者调用advancedBy()来指定访问相对位置的index( 之后5位的index: advancedBy(5) 往前5位的index: advancedBy(-5) )

let greeting = "Guten Tag!"
greeting[greeting.startIndex] //G
greeting[greeting.endIndex.predecessor()]  //!
greeting[greeting.startIndex.advancedBy(2)] //t

indiced:字符串Index的集合

for index in greeting.characters.indices {
    print("\(greeting[index])",terminator:"!")
}
// G!u!t!e!n! !T!a!g!!!

插入/移除

//插入/移除 insert(_:atIndex:)方法
var welcome1 = "hello"
welcome.insert("!", atIndex: welcome1.endIndex)
// welcome now equals "hello!"

//使用insertContentsOf(_:at:) 方法
welcome.insertContentsOf(" there".characters, at: welcome.endIndex.predecessor())
// welcome now equals "hello there!"

//使用removeAtIndex(_:)方法
welcome.removeAtIndex(welcome.endIndex.predecessor())
// welcome now equals "hello there"

//使用removeRange(_:)方法
let range = welcome.endIndex.advancedBy(-6)..<welcome.endIndex
welcome.removeRange(range)
// welcome now equals "hello"

移除(index)

var helloStr3 = "hello world!"
let range = helloStr3.endIndex.advancedBy(-6) ..< helloStr3.endIndex //6..<12
helloStr3.removeRange(range)  //"hello"

字符串比较
字符串相等

let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    print("These two strings are considered equal")
}
// Prints "These two strings are considered equal"

前缀和后缀比较 使用 hasPrefix()和hasSuffix()去匹配String的前缀和后缀返回一个Boolean

let remeoAndJuliet = [
    "Act 1 Scene 1: Verona, A public place",
    "Act 1 Scene 2: Capulet's mansion",
    "Act 1 Scene 3: A room in Capulet's mansion",
    "Act 1 Scene 4: A street outside Capulet's mansion",
    "Act 1 Scene 5: The Great Hall in Capulet's mansion",
    "Act 2 Scene 1: Outside Capulet's mansion",
    "Act 2 Scene 2: Capulet's orchard",
    "Act 2 Scene 3: Outside Friar Lawrence's cell",
    "Act 2 Scene 4: A street in Verona",
    "Act 2 Scene 5: Capulet's mansion",
    "Act 2 Scene 6: Friar Lawrence's cell"
]
//遍历字符数组 匹配前缀
var count = 0
for str in remeoAndJuliet {
    if str.hasPrefix("Act 1") {
        count++
    }
}
print("There are \(count) string with Act 1")
//"There are 5 string with Act 1\n"

利用 hasPrefix 方法使用 romeoAndJuliet 数组来计算话剧中第一幕的场景数:

var act1SceneCount = 0
for scene in romeoAndJuliet {
    if scene.hasPrefix("Act 1 ") {
        act1SceneCount += 1
    }
}
print("There are \(act1SceneCount) scenes in Act 1")
// Prints "There are 5 scenes in Act 1"

使用 hasSuffix 方法来计算发生在 Capulet 公馆和 Lawrence 牢房内以及周围的场 景数。

var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
    if scene.hasSuffix("Capulet's mansion") {
        mansionCount += 1
    } else if scene.hasSuffix("Friar Lawrence's cell") {
        cellCount += 1
    }
}
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// Prints "6 mansion scenes; 2 cell scenes"

大写和小写字符串

let normal = "Could you help me, please"
let shouty = normal.uppercaseString  //"COULD YOU HELP ME, PLEASE"
let whispered = normal.lowercaseString //"could you help me, please"
let captital = normal.capitalizedString //"Could You Help Me, Please"

Unicode 术语(Terminology)

let dogString = "Dog!????"

for codeUnit in dogString.utf8 {
    print("\(codeUnit)")
}
print("\n")
//68 111 103 33 240 159 144 182

for scalar in dogString.unicodeScalars {
    print("\(scalar) ")
    }
/*
D
o
g
!
?
?
?
?
*/



https://www.xamrdz.com/lan/5e41957257.html

相关文章: