String and character (strings and characters)
Content on this page:
- String Literal
- Initialize an empty string
- String Variability
- String is a value type
- Characters Used
- Count characters
- Connection string and character
- String Interpolation
- Comparison string
- String case
- Unicode
String
It's an ordered format like "hello, World" and "one piece ".Character
(Character) type value set, throughString
Type.
SwiftString
AndCharacter
Type provides a fast and Unicode-compatible way to process text information in the code. The syntax for creating and operating strings is similar to that for string operations in C. It is lightweight and easy to read. To connect strings, you only need+
Connect the two strings. Like other values in swift, whether a string value can be changed depends on whether it is defined as a constant or a variable.
Although the syntax is simpleString
Type is a fast and modern string implementation. Each string is composed of Unicode characters of independent encoding and supports access to these characters in different Unicode representations.
Swift can perform string interpolation in constants, variables, literal quantities, and expressions to easily create custom strings for display, storage, and printing.
Note:
SwiftString
Type and FoundationNSString
Class. If you work with the foundation framework in cocoa or cocoa touch. AllNSString
You can call anyString
Type value. In addition, you can also useString
Features. You can also specifyNSString
The instance is used as a parameter in the APIString
Type value as an alternative. For more information about how to use it in foundation and cocoaString
For more information, see using SWIFT with cocoa and objective-C.
String Literal (string literals)
You can include a predefined string value in your code as a string literal. String Literal is a character set with a fixed sequence wrapped by double quotes.
A string literal can be used to provide an initial value for constants and variables.
let someString = "Some string literal value"
Note:
someString
The constant is initialized by the string literal, so swift determines that the constant isString
Type.
A string literal can contain the following special characters:
- Escape characters
\0
(Null character ),\\
(Backslash ),\t
(Horizontal tab ),\n
(Line Break ),\r
(Carriage return ),\"
(Double quotation marks ),\‘
(Single quotes ).
- Single-byte Unicode scalar, written
\xnn
, Wherenn
It is a two-digit hexadecimal number.
- Double-byte Unicode scalar, written
\unnnn
, Wherennnn
It is a four-digit hexadecimal number.
- Four-byte Unicode scalar, written
\Unnnnnnnn
, Wherennnnnnnn
It is an octal hexadecimal number.
The following code is an example of special characters.wiseWords
A constant contains two special characters for transfer (double parentheses );dollarSign
,blackHeart
AndsparklingHeart
Constants demonstrate Unicode flags in three different formats:
Let wisewords = "\" I am the man who wants to be a pirate king \ "-lufei" // "I am the man who wants to be a pirate king"-lufei let dollarsign = "\ x24" // $, unicode scalar U + 0024let Blackheart = "\ u2665 "//♥, Unicode scalar U + 2665let sparklingheart = "\ u0001f496 "//??, Unicode scalar U + 1f496
Initialize an empty string (initializing an empty string)
To construct a long string, you can create an empty string as the initial value. You can assign an empty string literal to a variable or initialize a newString
Instance:
VaR emptystring = "" // empty string literal var anotheremptystring = string () // initialize the string instance // both strings are null and equivalent.
You can check itsBoolean
TypeisEmpty
Attribute to determine whether the string is null:
If emptystring. isempty {println ("nothing")} // print the output: "nothing"
String mutability)
You can assign a specific string to a variable to modify it, or assign it to a constant to ensure that it will not be modified:
VaR variablestring = "horse" variablestring + = "and carriage" // variablestring is now "horse and carriage" Let constantstring = "Highlander" constantstring + = "and another Highlander" // This will report a compilation error (compile-time error) -constants cannot be modified.
Note:
In objective-C and cocoa, you can select two different classes (NSString
AndNSMutableString
) To specify whether the string can be modified, and whether the string in Swift can be modified is determined only by defining the variable or constant, achieving the unification of multiple types of variability operations.
String is a value type (strings are value types)
SwiftString
Type is the value type. If you create a new string, the value is copied when it is used to assign values to constants or variables, or when it is passed in a function/method. Under any circumstances, a new copy of an existing string value is created, and the new copy is passed or assigned a value. The value types are described in struct and enumeration are value types.
Note:
In cocoaNSString
Different, when you createNSString
Instance, and pass it to a function/method, or assign a value to a variable.NSString
A reference of an instance. Unless you require copying the value, the string will not generate a new copy for value assignment.
Swift's default string copy method ensures that the string value is passed in the function/method. Obviously, no matter where the value comes from, you own it. You can rest assured that the string you pass will not be changed.
During actual compilation, the swift compiler optimizes the use of strings so that the actual replication only occurs when absolutely necessary, this means that when you use a string as a value type, you can achieve extremely high performance.
Working with characters)
SwiftString
Type indicatesCharacter
A set of (character) type values. Each character value represents a Unicode character. You can usefor-in
Loop to traverse every character in the string:
for character in "Dog!??" { println(character)}// D// o// g// !// ??
The for-in loop is described in detail in for loops.
In addition, by specifyingCharacter
You can create an independent character constant or variable by specifying the type annotation and assigning values using the character literal:
let yenSign: Character = "¥"
Count characters)
By calling GlobalcountElements
Function, and pass the string as a parameter to obtain the number of characters in the string.
Let unusualmenagerie = "Koala ??, Snail il ??, Penguin ??, Dromedary ?? "Println (" unusualmenagerie has \ (countelements (unusualmenagerie) characters ") // print the output:" unusualmenagerie has 40 characters"
Note:
Different Unicode characters and different Representation Methods of the same UNICODE character may require different amounts of memory space for storage. Therefore, the characters in swift do not necessarily occupy the same memory space in a string. Therefore, the length of a string must be calculated by the length of each character in the iterated string. If you are processing a long string, note thatcountElements
The function must traverse characters in the string to accurately calculate the length of the string. In addition, you must note thatcountElements
The number of returned characters is not always the same as thatNSString
Oflength
Same attributes.NSString
Oflength
The attribute is based on the number of sixteen-bit code units represented by a UTF-16, rather than Unicode characters. To solve this problem,NSString
Oflength
The property is inString
Theutf16count
.
Concatenating strings and characters)
You can use the addition operator (+
) And create a new string:
Let string1 = "hello" Let string2 = "there" Var welcome = string1 + string2 // welcome is now equal to "Hello there"
You can also use the addition assignment operator (+=
) Add a string to an existing string variable:
VaR instruction = "Look over" Instruction + = string2 // instruction is now equal to "look over there"
You can useappend
Method to append a character to the end of a string variable:
Let exclamationmark: character = "! "Welcome. append (exclamationmark) // welcome is equal to" Hello there! "
Note:
You cannot add a string or character to an existing character variable, because the character variable can only contain one character.
String Interpolation)
String interpolation is a way to create a new string. It can contain constants, variables, literal quantities, and expressions. Each item of the string literal you insert is enclosed in parentheses prefixed with a backslash:
Let multiplier = 3let message = "\ (multiplier) multiplied by 2.5 is \ (double (multiplier) * 2.5)" // message is "3 multiplied by 2.5 is 7.5"
In the preceding example,multiplier
As\(multiplier)
Is inserted into a string literal. This placeholder is replacedmultiplier
The actual value.
multiplier
Is also part of the string expression. This expression is used for calculation.Double(multiplier) * 2.5
And insert the result (7.5) into the string. In this example, the expression is written\(Double(multiplier) * 2.5)
It is included in the string literal.
Note:
The expressions written in parentheses in the interpolation string cannot contain non-escape double quotation marks ("
) And backslash (\
And cannot contain carriage return or line break.
Comparison string (comparing strings)
Swift provides three methods to compare string values: equal strings, equal prefixes, and equal suffixes.
String equality)
If the two strings contain identical characters in the same order, the two strings are considered equal:
Let quotation = "we are the same. "Let samequotation =" we are the same. "If quotation = samequotation {println (" the two strings are considered the same ")} // print the output:" These two strings are considered the same"
Equal prefix/suffix (prefix and suffix fill ity)
By calling the stringhasPrefix
/hasSuffix
To check whether the string has a specific prefix or suffix. Both methods must be passed in and passed out using strings as parameters.Boolean
Value. Both methods perform character-by-character comparison between the basic string and the prefix/suffix string.
The following example uses a string array to represent the location of the first two scenes in Shakespeare's play "Romeo and Juliette:
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 usehasPrefix
Method to calculate the number of scenes in the first scene of a drama:
VaR act1scenecount = 0for scene in romeoandjuliet {If scene. hasprefix ("act 1") {++ act1scenecount} println ("there are \ (act1scenecount) scenes in Act 1") // print the output: "There are 5 scenes in Act 1"
Similarly, you can usehasSuffix
Method to calculate the number of scenarios that occur in different places:
VaR mansioncount = 0var cellcount = 0for scene in romeoandjuliet {If scene. hassuffix ("Capulet's mansion") {++ mansioncount} else if scene. hassuffix ("Friar Lawrence's cell") {++ cellcount} println ("\ (mansioncount) mansion scenes; \ (cellcount) cell scenes") // print the output: "6 mansion scenes; 2 cell scenes"
Upper and lower case strings (uppercase and lowercase strings)
You can useuppercaseString
AndlowercaseString
Attribute to access strings in uppercase/lowercase.
Let normal = "cocould you help me, please? "Let shouty = normal. uppercasestring // The shouty value is" cocould you help me, please? "Let whispered = normal. lowercasestring // The whispered value is" cocould you help me, please? "
Unicode
Unicode is an international standard used for text encoding and representation. It allows you to use standard format to represent almost all characters from any language, and to read and write characters in external resources such as text files or webpages.
Swift's string and character types are fully compatible with the Unicode Standard and support a series of different Unicode encodings described below.
Unicode terminology)
Each character in Unicode can be interpreted as one or more Unicode scalar. The Unicode scalar of a character is a unique 21-bit number (and name), suchU+0061
Lowercase Latin letter A (""),U+1F425
It indicates a chicken expression ("?? ")
When Unicode strings are written into text files or other storage structures, These unicode flags are encoded according to one of the Unicode-defined centralized formats. IncludingUTF-8
(Encoded in 8-bit code units) andUTF-16
(Encoded in 16-bit code units ).
Unicode representation of strings (UNICODE representations of strings)
Swift provides several different methods to access the Unicode representation of strings.
You can usefor-in
To traverse the string and access each character value as a Unicode character. This process is described in characters.
In addition, you can access the value of a string in three other Unicode-compatible ways:
- A collection of UTF-8 code units (using a string's
utf8
Attribute)
- A collection of UTF-16 code units (using a string's
utf16
Attribute)
- A 21-bit set of Unicode scalar values (using
unicodeScalars
Attribute)
TheD``o``g``!
And??
(DOG FACE
, Unicode scalar isU+1F436
Each character in a string represents a different representation:
let dogString = "Dog!??"
UTF-8
You can traverseutf8
Attribute to access itsUTF-8
. It isUTF8View
Type attribute,UTF8View
Is an unsigned 8-bit (UInt8
) Value set, eachUInt8
The value is a UTF-8 representation of a character:
for codeUnit in dogString.utf8 { print("\(codeUnit) ")}print("\n")// 68 111 103 33 240 159 144 182
In the preceding example, the first four 10 hexadecimal code unit values (68,111,103, 33) represent characters.D
o
g
And!
, Their UTF-8 representation is the same as ASCII representation. The last four code unit values (240,159,144,182) areDOG FACE
4-byte UTF-8 representation.
UTF-16
You can traverseutf16
Attribute to access itsUTF-16
. It isUTF16View
Type attribute,UTF16View
Is an unsigned 16-bit (UInt16
) Value set, eachUInt16
Is a UTF-16 representation of a character:
for codeUnit in dogString.utf16 { print("\(codeUnit) ")}print("\n")// 68 111 103 33 55357 56374
Similarly, the first four code unit values (68,111,103, 33) represent charactersD
o
g
And!
, They have identical UTF-16 code units and UTF-8.
The fifth and sixth code unit values (55357 and 56374) areDOG FACE
The UTF-16 representation of the character. The first value isU+D83D
(Decimal value: 55357), the second value isU+DC36
(Decimal value: 56374 ).
Unicode scalars)
You can traverseunicodeScalars
Attribute to access its Unicode scalar representation. It isUnicodeScalarView
Type attribute,UnicodeScalarView
YesUnicodeScalar
.UnicodeScalar
Is a 21-bit Unicode Code Point.
EveryUnicodeScalar
Has a value attribute, and can return the corresponding 21-digit value,UInt32
.
for scalar in dogString.unicodeScalars { print("\(scalar.value) ")}print("\n")// 68 111 103 33 128054
Similarly, the first four code unit values (68,111,103, 33) represent charactersD
o
g
And!
. The fifth digit, 128054, is a hexadecimal 1f436 decimal representation. It is equivalentDOG FACE
Unicode scalar U + 1f436.
As an alternative to querying character value attributes, eachUnicodeScalar
The value can also be used to construct a new string value, for example, in string interpolation:
for scalar in dogString.unicodeScalars { println("\(scalar) ")}// D// o// g// !// ??
Reprinted: http://numbbbbb.gitbooks.io/-the-swift-programming-language-/chapter2/03_Strings_and_Characters.html
String and character (strings and characters)