斯威夫特山地车_斯威夫特弦乐

斯威夫特山地车

Today we will look into Swift String operations. Furthermore, we’ll be discussing the changes in Strings with the introduction of Swift 4. Earlier we looked into Swift Function. Let’s open up our playground and dive right in.

今天,我们将研究Swift String操作。 此外,随着Swift 4的引入,我们将讨论Strings中的更改。 之前我们研究过Swift函数 。 让我们打开我们的游乐场并立即潜水。

斯威夫特弦乐 (Swift String)

String in Swift is an ordered collection of values which are of the type Character.

Swift中的String是类型为Character的值的有序集合。

Similar to Arrays, String defined with var are mutable and strings defined with let keyword are immutable.

与数组类似,用var定义的字符串是可变的,而用let关键字定义的字符串是不可变的。

Changes with Swift 4:
Now Strings conform to the collections protocol.
Hence Strings are Collections..
Methods such as reversed(), indexOf() etc that are applicable to collections are now applicable with Swift Strings directly too without the use of characters

Swift 4的变化
现在,字符串符合集合协议
因此,字符串是集合。
适用于集合的诸如reversed()indexOf()等方法现在也可以直接用于Swift Strings,而无需使用characters

Swift String初始化 (Swift String initialization)

There are numerous ways to initialize a String in Swift.

在Swift中有很多初始化String的方法。

//initializing an empty string
var empty = ""            // Empty String
var anotherEmpty = String()       // Another way to initialize an empty string

var str = "Hello, playground" //String literal
var intToString = String(10) // returns "10", this can be used to convert any type to string
var boolToString = String(false) // returns "false"

//initialise a string using repeating values.
let char = "a"
let string = String(repeating: char, count: 5) //prints "aaaaa"
let newChar = "ab"
let newString = String(repeating: newChar, count: 5) //prints : "ababababab"

A string literal is a sequence of characters surrounded by double quotes (“).

字符串文字是由双引号(“)引起的一系列字符。

Swift String空字符串检查 (Swift String Empty String check)

To check if a string is empty or not we invoke the function isEmpty as shown below.

要检查字符串是否为空,我们调用isEmpty函数,如下所示。

var empty = ""
var boolToString = String(false) // returns "false"

if empty.isEmpty
{
 print("string is empty")
}

if !boolToString.isEmpty
{
 print("string is not empty")
}

附加字符串 (Appending Strings)

Strings and characters can be appended to a string using the append() function or the += operator as shown below.

可以使用append()函数或+=运算符append()字符串和字符附加到字符串,如下所示。

var myString =  "Hello"
myString += " World" //returns "Hello World"
myString.append("!") //returns "Hello World!"
print(myString) //prints "Hello World!\n"

字符串插值 (String Interpolation)

String interpolation is a way to construct a new String value from a mix of constants and variables.
Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash (\) as shown below:

字符串插值是一种通过混合使用常量和变量来构造新的String值的方法。
插入字符串文字中的每个项目都用一对括号括起来,并以反斜杠(\)为前缀,如下所示:

let multiplier = 2
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" //prints "2 times 2.5 is 5.0"

遍历字符串 (Iterating through a String)

Iterating over a String to fetch each character in Swift 3 is done using a for-in loop in the following manner(s):

使用for-in循环以以下方式对String进行迭代以获取Swift 3中的每个字符:

//using characters property
for character in myString.characters
{
 print(character)
}

//using indices property.
for character in myString.characters.indices
{
 print(myString[character])
}
//using enumerated() func
for (index,character) in myString.characters.enumerated()
{
 print(character)
}
//prints:
H
e
l
l
o
 
W
o
r
l
d
!

enumerated() : Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence.

enumerated() :返回一个对对(n,x)的序列,其中n表示一个从零开始的连续整数,x表示该序列的一个元素。

Changes in Swift 4:
characters is now deprecated in Swift 4.

Swift 4的变化:
Swift 4中不推荐使用这些characters

Retrieving characters in swift 4.

快速检索字符4。

for character in myString {
    print(character)
}

快速字符串长度 (Swift String Length)

Length of a string is retrieved as follows.

字符串的长度如下检索。

let myString = "Too many characters here!"
print(myString.characters.count) //prints 25

Successive properties namely characters and count are used to get the length of a string.

连续属性(即characterscount用于获取字符串的长度。

In Swift 4:
To get the length of a Swift String we just need to call myString.count.

在Swift 4中:
要获取Swift String的长度,我们只需要调用myString.count

多行字符串文字 (Multi-Line String Literals)

With Swift 4 following is the way to define a multiline string literals using triple quotes:

在Swift 4中,以下是使用三引号定义多行字符串文字的方法:

let multiLineString = """
Line 1
Line 2 goes here
Line 3 goes here
"""

Swift 4 compiler adds a new line by default at the end of each line.
To prevent this default behavior we need to use a backslash (\).

Swift 4编译器默认在每一行的末尾添加新行。
为了防止这种默认行为,我们需要使用反斜杠(\)。

let multiLineString = """
Line 1
Line 2 goes here, \
Line 3 goes here
"""
print(multiLineString)
//Prints
//Line 1
//Line 2 goes here, Line 3 goes here

字符串比较 (String Comparison)

Swift String doesn’t have equals method like other languages. It checks the values using == and !=

Swift String没有其他语言一样具有equals方法。 它使用==!=检查值

var stringA = "string"
var stringB = "string"
var stringC = "new string"
stringA == stringB //prints true
stringB != stringC //prints true

Swift中字符串的重要功能 (Important Functions for Strings in Swift)

Swift provides quite a number of powerful functions that can be used for performing operations on Strings.
The best thing about these functions is the high level of readability they’ve got to offer.

Swift提供了许多强大的函数,可用于对String执行操作。
这些功能的最好之处在于它们具有很高的可读性。

转换为大写和小写 (Convert to upper and lower case)

var myString = "Hello World!"
myString.lowercased() returns "hello world!"
myString.uppercased() //returns "HELLO WORLD!"

前缀和后缀 (Prefix and Suffix)

myString.hasPrefix("Hello") //returns true
myString.hasPrefix("hello") //returns false
myString.hasSuffix("!") //returns true

//Alternative approach
String(myString.characters.prefix(2)) //returns "He"
String(myString.characters.suffix(3)) //returns "ld!"

prefix(maxLength) and suffix(maxLength) returns a substring with the first and last n number of characters respectively based on the number entered.

prefix(maxLength)suffix(maxLength)返回一个子字符串,该子字符串根据输入的数字分别具有前n个字符和后n个字符。

字符串开始和结束索引 (String start and end index)

var myString = "Hello World!"
myString.startIndex //returns 0
myString.endIndex //returns 12

从字符串插入和删除字符 (Insert and remove character from String)

myString.insert("!", at: myString.endIndex) // "Hello World!!"
myString.insert("!", at: myString.startIndex) // "!Hello World!!"
myString.remove(at: myString.startIndex) //returns "!"
print(myString) // "Hello World!!\n"

Note: at: expects an argument of type String.Index. Int won’t work(Atleast not in Swift 3)

注意at:需要一个String.Index类型的参数。 诠释将不起作用(Atleast在Swift 3中不适用)

插入多个字符/子字符串 (Insert multiple characters/substring)

myString.insert(contentsOf: "Hey".characters, at: myString.endIndex) // returns "Hello World!Hey"

检索其他索引 (Retrieve other indexes)

var myString = "Hello World!"
let startIndexPlusTwo = myString.index(myString.startIndex, offsetBy: 2)
let endIndexMinusFour = myString.index(myString.endIndex, offsetBy: -4)
myString[startIndexPlusTwo] //returns "l"
myString[endIndexMinusFour] //returns "r"
myString[myString.index(before: startIndexPlusTwo)] // returns "e"
myString[myString.index(after: startIndexPlusTwo)] //returns "l"

startIndexPlusTwo and endIndexMinusFour is of the type String.Index. Only type String.Index is accepted inside myString[]. Not Int.

startIndexPlusTwo和endIndexMinusFour的类型为String.IndexmyString[]内部仅接受String.Index类型。 不是Int。

字符索引 (Index of a character)

var myString = "Hello World!"
myString.characters.index(of: "o") // returns 4
myString.characters.index(of: "f") // returns nil

index(of:) returns the index of the first matching character

index(of:)返回第一个匹配字符的索引

Swift String子字符串 (Swift String substring)

We can retrieve a substring between indexes as follows.

我们可以按如下方式检索索引之间的子字符串。

var myString = "Hello World!"
let startIndexPlusTwo = myString.index(myString.startIndex, offsetBy: 2) 
let endIndexMinusFour = myString.index(myString.endIndex, offsetBy: -4)
myString[startIndexPlusTwo..<myString.endIndex] //returns "llo World!"
myString[myString.startIndex..<startIndexPlusTwo] //returns "He"

//Alternate approach
myString.substring(to: startIndexPlusTwo) //returns "He"
myString.substring(from: startIndexPlusTwo) //returns "llo World!"
myString.substring(with: startIndexPlusTwo..<endIndexMinusFour) // "llo Wo"
var mySubString = String(myString.characters.suffix(from: startIndexPlusTwo)) //returns "llo World!"

substring(to:) returns the substring from the startIndex to the index set.
substring(from:) returns the substring from the index set to the end index.
substring(with:) returns the substring between the range of indexes entered.

substring(to:)将子字符串从startIndex返回到索引集。
substring(from:)返回从索引集到结束索引的子字符串。
substring(with:)返回输入的索引范围之间的子字符串。

搜索子字符串 (Search For A Substring)

Searching for a substring is done using the function range(of:). This function returns an optional type which is a range of indexes of the type Range?, hence we’ll need to unwrap it to use the range.

使用功能range(of:)搜索子字符串。 此函数返回一个可选类型,该类型是Range?类型的索引Range? ,因此我们需要对其进行包装以使用范围。

if let myRange = myString.range(of: "Hello"){
myString[myRange] //returns "Hello"
}
else{
 print("No such substring exists")
}
//In case when the substring doesn't exist
if let myRange = myString.range(of: "Hlo"){
myString[myRange]
}
else{
 print("No such substring exists") //this is printed
}

从Swift字符串中替换/删除子字符串 (Replacing/Removing a Substring from Swift String)

The functions replaceSubrange and removeSubrange are used for replacing and removing a substring from a string as shown below.

函数replaceSubrangeremoveSubrange用于替换字符串中的子字符串,如下所示。

var myString = "Hello World!"
//replacing
if let myRange = myString.range(of: "Hello"){
myString.replaceSubrange(myRange, with: "Bye") //returns "Bye World!"
}
else{
 print("No such substring exists")
}

//removing
if let myRange = myString.range(of: "Hello "){
myString.removeSubrange(myRange) //returns "World!"
}
else{
 print("No such substring exists")
}

Swift String分割 (Swift String split)

To split a string we use the function components(separatedBy:). The function expects a parameter of the type Character or String as shown below:

为了分割字符串,我们使用了components(separatedBy:)函数。 该函数需要一个类型为Character或String的参数,如下所示:

var myString = "Hello How You Doing ?"
var stringArray = myString.components(separatedBy: " ") //returns ["Hello", "How", "You", "Doing", "?"]
for string in stringArray
{
    print(string)
}
//prints:
Hello
How
You
Doing
?

Changes in Swift 4: Swift 4 has made Substring as a type too along with String.

Swift 4中的更改 :Swift 4也使SubstringString一起成为一种类型。

子串作为一种类型 (Substring as a type)

Substring which is a subsequence of strings is also a type now. Hence when we split the string in Swift 4, we get an array of Substring type. Each of the elements is of the type Substring as shown below.

现在,作为字符串子序列的子字符串也是一种类型。 因此,当我们在Swift 4中分割字符串时,我们得到一个Substring类型的数组。 每个元素都是Substring类型,如下所示。

var myString = "Hello How You Doing ?"
var substrings = myString.split(separator: " ")
type(of: substrings) //Array<Substring>.Type
type(of: substrings.first!) //Substring.Type
var newStringFromSub = String(substrings.first!) // "Hello"

Note: type is a function which returns the type of the argument passed.

注意: type是一个函数,它返回传递的参数的类型。

This brings an end to Swift String tutorial. We’ve covered all the bases and implementation of Strings in Swift and also discussed the new changes in Swift 4.

这样就结束了Swift String教程。 我们已经介绍了Swift中String的所有基础和实现,还讨论了Swift 4中的新变化。

翻译自: https://www.journaldev.com/15313/swift-string

斯威夫特山地车

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值