Swift tutorials for string and character details _swift

Source: Internet
Author: User
Tags constant lowercase scalar

A string is a sequence of characters, such as "Hello,world", "Albatross". The strings in Swift are defined by string keywords, and it is also a collection of characters, defined by character.

Swift's string and character types provide the code with a fast, Unicode-compliant character solution. The initialization and use of string types are readable and similar to the strings in C. String can also be combined by using the + operator, which is as simple as using other basic types in Swift.

1. String constants

You can use string constants that are predefined by string in your code, and are defined in a very simple way:

Copy Code code as follows:

Let somestring = "Some string literal value"

String constants can include the following special characters:

Null characters, backslash \, tab \ \ n, newline, carriage return \ r, double quotes \ "and single quotes \"

Single-byte Unicode character, \xnn, where nn is two hexadecimal digits

Double-byte Unicode character, \unnnn, where nnnn is four hexadecimal digits

Four-byte Unicode character, \unnnnnnnn, where nnnnnnnn is eight hexadecimal digits

The following code gives examples of these four types of strings:

Copy Code code as follows:

Let wisewords = "\" Imagination are more important than knowledge\ "-Einstein"
"Imagination is more important than knowledge"-Einstein
Let dollarsign = "\x24"//$, Unicode scalar u+0024
Let Blackheart = "\u2665"//♥, Unicode scalar u+2665
Let Sparklingheart = "\u0001f496"//, Unicode scalar u+1f496

2. Initialize an empty string

There are two forms of initializing an empty string, but the results of both initialization methods are the same, representing an empty string

Copy Code code as follows:

var emptystring = ""//empty string literal
var anotheremptystring = String ()//initializer syntax
These two strings are both empty, and are equivalent to

You can check whether a string is empty by using the IsEmpty property
Copy Code code as follows:

If Emptystring.isempty {
println ("Nothing to the Here")
}
Prints "nothing to"

3, variable length string

If the string defined with the var keyword is a variable-length string that can be modified, the string defined by the Let keyword is a constant string and cannot be modified.

Copy Code code as follows:

var variablestring = "Horse"
variablestring = "and carriage"
Variablestring is now "horse and carriage"
Let constantstring = "Highlander"
Constantstring = "and another Highlander"
This reports a Compile-time ERROR-A constant string cannot to be modified

4, the string is not a pointer, but the actual value

In Swift, a string type is an actual value, and when a new string is defined and the previous string value is copied, it is actually creating an equal new value instead of just pointing to the past like a pointer.

Also, when the function passes the argument, the actual value is passed, and a new string is created, and subsequent operations do not change the original string string.

5, character

Swift's strings string is composed of character character, each of which represents a particular Unicode character. Character By for-in loops, you can traverse each character in a string:

Copy Code code as follows:

For character in "dog!" {
println (character)
}
D
O
G
// !
//

You can also simply define a single character:

Copy Code code as follows:

Let Yensign:character = "¥"

6, character count

Use global functions countelements to calculate the number of characters in a string:

Copy Code code as follows:

Let Unusualmenagerie = "Koala, Snail, Penguin, dromedary"
println ("Unusualmenagerie has \ countelements (Unusualmenagerie)) characters")
Prints "Unusualmenagerie has characters"

7. Using characters and strings in combination

String and character types can be combined into a new string by using the + number addition

Copy Code code as follows:

Let string1 = "Hello"
Let string2 = "there"
Let Character1:character = "!"
Let Character2:character = "?"
Let Stringpluscharacter = string1 + character1/equals "hello!"
Let stringplusstring = string1 + string2/equals "Hello there"
Let characterplusstring = Character1 + string1/equals "!hello"
Let Characterpluscharacter = Character1 + character2/equals "!?"

You can also use the + = number to combine:

Copy Code code as follows:

var instruction = "Look over"
Instruction + + string2
Instruction now equals "look over There"
var welcome = "Good Morning"
Welcome + + Character1
Welcome now equals "Good morning!"

8. Using strings to generate new strings

With an existing string, you can use the following method to generate a new string:

Copy Code code as follows:

Let multiplier = 3
Let message = ' (multiplier) times 2.5 is \ (Double (multiplier) * 2.5) "
Message was "3 times 2.5 is 7.5"

In the above example, the first use of the multiplier string 3 as part of the new string is added with (multiplier), and the example above also uses the type conversion double (multiplier). Adds the result of the calculation and the string itself as an element to the new string.

9, string comparison

Swift provides three methods to compare string values: equal strings, prefixes equal, and suffixes equal
String equality
When two strings contain exactly the same characters, they are judged to be equal.

Copy Code code as follows:

Let quotation = "We ' re a lot alike, you and I."
Let samequotation = "We ' re a lot alike, you and I."
If quotation = = Samequotation {
println ("These two strings are considered equal")
}
Prints "These two strings are considered equal"
Output "These two strings are considered equal"

Prefix (prefix) equality and suffix (hassuffix) equality

Use the two methods of the string class Hasprefix and Hassuffix to check whether the prefix or suffix of a string contains another string, it requires a string type argument and a value that returns a Boolean type. Two methods do between characters and between the original string and the prefix string or the suffix string.

In the following example, a string array is used to reproduce the scene of Shakespeare's first two scenes of Romeo and Juliet.

Copy Code code as follows:

Let Romeoandjuliet = [
"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"
]

You can use the Hasprefix method and the Romeoandjuliet array to figure out how many scenes to perform in the first act.

Copy Code code as follows:

var act1scenecount = 0
For scene in Romeoandjuliet {
If Scene.hasprefix ("Act 1") {
++act1scenecount
}
}
println ("There are \ act1scenecount) scenes in Act 1")
Output "There are 5 scenes in Act 1"

Similarly, using the Hassuffix method to calculate how many scenes occurred in Capulet mansion and Friar Lawrence Cell

Copy Code code as follows:

var mansioncount = 0
var cellcount = 0
For scene in Romeoandjuliet {
If Scene.hassuffix ("Capulet ' Mansion") {
++mansioncount
else if Scene.hassuffix ("Friar Lawrence ' s cell") {
++cellcount
}
}
println ("\ (mansioncount) mansion scenes; \ (cellcount) cell scenes ")
Output "6 mansion scenes; 2 cell scenes "

Case string

You can get an uppercase or lowercase character from a string of uppercasestring and lowercasestring.

Copy Code code as follows:

Let normal = "could for help me, please?"
Let shouty = normal.uppercasestring
shouty is equal to "could you help ME, please?"
Let whispered = normal.lowercasestring
Whispered is equal to "could you help me, please?"

10, Unicode

Unicode is an international standard for encoding and representing text. It can almost show the standard form of all the characters in all languages. You can also read and modify their characters from external source files such as text files or Web pages.

Unicode terminology

Each Unicode character can be encoded as one or more Unicode scalar. A Unicode scalar is a unique 21-digit number (or name) that corresponds to a character or identity. For example u+0061 is a lowercase a ("a"), or u+1f425 is a yellow chick facing us

When a Unicode string is written to text or other storage, the Unicode scalar is encoded according to the format of the Unicode definition. Each formatted encoded character is a small block of code that is called the units. He contains the UTF-8 format (each string consists of 8-bit code units). and UTF-16 format (each string consists of 16-bit code units)

Unicode string

Swift supports a number of different ways to get Unicode strings.
You can use the For-in statement to traverse a string to get the Unicode encoding value of each character. This process has been described in characters (Working with Characters).
Alternatively, use the appropriate one in the following three descriptions to get the value of a string
UTF-8 character encoding unit collection using the String type Utf-8 property
UTF-16 character encoding unit collection using the String type Utf-16 property
21-bit Unicode scalar collection using the String type Unicodescalars property
Each of the following examples shows a different coding display by D, O, G,!

A string of (DOG face, or Unicode scalar u+1f436) characters
UTF-8
you can use the String type UTF8 property to traverse a UTF-8 encoded string. This property is Utf8view type
, Utf8view is a collection of 8-bit unsigned reshaping (UInt8) in which each byte in the collection is UTF-8 encoded.

Copy Code code as follows:

For codeunit in Dogstring.utf8 {
Print ("\ (codeunit)")
}
Print ("\ n")
68 111 103 33 240 159 144 182

In the above example, the first 4 decimal codeunit values (68,111,103,33) appear as Strings D, O, G, and! , and they have the same ASCII encoding. The value of the following 4 codeunit (240,159,144,182) is the 4-byte UTF-8 encoding of the dog face character.

UTF-16

You can use the String type Utf16 property to traverse a UTF-16 encoded string. This property is the Utf16view type, Utf16view is a collection of 16-bit unsigned reshaping (UInt16) in which each byte in the collection is UTF-16 encoded.

Copy Code code as follows:

For codeunit in Dogstring.utf16 {
Print ("\ (codeunit)")
}
Print ("\ n")
68 111 103 33 55357 56374

Similarly, the first 4 decimal codeunit values (68,111,103,33) appear as Strings D, O, G, and! , their UTF-16 codeunit are the same as their UTF-8 encoded values.
The 5th and 6th codeunit values (55357 and 56374) are proxy pairs encoded by the UTF-16 of the dog face character. Their values are composed of a high agent (lead surrogate) with a value of u+d83d (decimal 55357) and a low agent (trail surrogate) with a value of u+dc36 (decimal 56374).

Unicode scalar

You can use the String type Unicodescalars property to traverse a Unicode scalar-encoded string. This property is a Unicodescalarsview type, and Unicodescalarsview is a collection of unicodescalar types. Each Unicode scalar is an arbitrary 21-bit Unicode code bit, with no high proxy or low proxy.

Each unicodescalar uses the Value property to return a scalar 21-bit value, each of which is a value of 32-bit unsigned reshaping (UInt32):

Copy Code code as follows:

For scalar in Dogstring.unicodescalars {
Print ("\ (scalar.value)")
}
Print ("\ n")
68 111 103 33 128054

The Value property in the first 4 unicodescalar values (68,111,103,33) again shows the encoded characters D, O, G, and!. The fifth and final one unicodescalar is the dog face character, the decimal is 128054, equivalent to the 16-in 1f436, equivalent to the Unicode scalar u+1f436.
Each unicodescalar can be constructed into a new string instead of reading their Value property, similar to inserting a string.

Copy Code code as follows:

For scalar in Dogstring.unicodescalars {println ("\ (scalar)")}
D
O
G
// !
//

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.