斯威夫特山地车

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 stringvar 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
oW
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

斯威夫特山地车

斯威夫特山地车_斯威夫特弦乐相关推荐

  1. 斯威夫特山地车_斯威夫特| 两个数字相加的程序

    斯威夫特山地车 In this program, we will have an idea - how two numbers can be added and displayed as the ou ...

  2. 斯威夫特山地车_斯威夫特枚举

    斯威夫特山地车 In this tutorial, we'll be discussing the basics of Swift enum. You must be familiar with En ...

  3. 斯威夫特山地车_斯威夫特字典

    斯威夫特山地车 Swift Dictionary is one of the important collection types. Let's get started by launching th ...

  4. 无法嵌入互操作类型 请改用适用的接口_可微编程-自上而下的产品形态 4 Python互操作性...

    原文:Python互操作性 如设计概述文档所述,Python API互操作性是本项目的一个重要需求.虽然Swift被设计为与其他编程语言(及其运行时)集成,但动态语言的本质并不需要支持静态语言所需的深 ...

  5. 21世纪25大扣将排行榜(组图)

    21世纪25大扣将排行榜(组图) 编辑 | 删除 | 权限设置 | 更多▼ 设置置顶 推荐日志 转到私密记事本 ←¢聂風/ ☆    发表于2009年12月16日 08:38 阅读(1) 评论(0) ...

  6. 转:《音响世界》十年音响示范唱片

    <音响世界>十年音响示范唱片 一.知名度最高的10张示范唱片 01. 黑教堂 02. 小夜曲 03. 奶妈碟 ★ 美国TAS发烧名片+企鹅三星带花! 04. 长发妹 ★ 经典女声天碟 05 ...

  7. 故地重游-从唐家岭想起的过往

    今天是中秋节,放假总是感觉很没意思. 躺在床上看了半天<读者>,很无聊,骑着自行车出去转转. 其实早就想去唐家岭看看了,它让我想起好多辛酸的回忆... 为了在北京找工作,2009年在那里住 ...

  8. java山地自行车怎么看型号_怎么看捷安特山地车型号 请问有知道捷安特自行车型号...

    一般捷安特的车都会把型号印在车架上,都是英文的,比如ATX系列,OYEA系列.注意看车架上有没有标有ATXPRO或是数字型号.也可以登陆GIANT的官方网站,自行对比一下里面各种型号自行车的图片.捷安 ...

  9. java软尾山地车评测_[渣图] 骑很慢的穷屌丝软尾历程

    本帖最后由 keiya345 于 2018-2-16 22:10 编辑 一年前, 因女神也有骑山地车的原因, 我也开始了那不断自毒的日子 由几千块开始自毒, 一直到一万多, 再东问西寻后, 于是就有了 ...

最新文章

  1. Java应用程序中的性能改进:ORM / JPA
  2. linux mysql root修复_linux下误删mysql的root用户,解决方法
  3. bin(x) 将整数x转换为二进制字符串
  4. oracle连接数一直超出,Oracle超出最大連接數問題及解決(…
  5. 鸿蒙之下5怎么跳城池,鸿蒙之空间道尊
  6. MicroRNA Ranking(Tehran2016)
  7. 请写出3个Android布局,一起撸一波干货集中营练练手Android(三)布局+实现篇
  8. android 添加ga_android开发步步为营之70:android接入Google Analytics总结
  9. 蔬菜名称大全500种_96种室内盆栽植物图片及名称,室内植物品种大全
  10. 软件工程第一次测试——学生管理系统设计
  11. python tkinter背景图片_如何在tkinter中有背景图像和按钮?
  12. Java学习资料-java基本数据类型
  13. 163编辑器学习笔记
  14. MyBatis中foreach传入参数为Poji装饰类,list、数组的不同写法
  15. 小程序input textarea 禁止粘贴实现
  16. dos攻击防范 java_php DOS攻击实现代码(附如何防范)
  17. 面试题汇总11-20
  18. 小说:凡人修仙路基础
  19. 中文界面blend_Blend Modes v3.4 – unity混合模式插件
  20. 《狼图腾》--农耕民族与游牧民族的冲突

热门文章

  1. Android TelephonyManager类
  2. ASP.NET程序中常用代码汇总-1
  3. [转载] python下载安装教程
  4. [转载] Python OpenCV 基础教程
  5. [转载] python改写二分搜索算法_二分搜索算法模板python实现
  6. [转载] python中日期和时间格式化输出的方法
  7. [转载] python无法从nltk中调取文本 from nltk.book import *
  8. HTML5新增的表单类型
  9. 路漫漫其修远兮,吾要上下左右前后而求索
  10. FlowNet: Learning Optical Flow with Convolutional Networks