Fourth chapter: Strings and characters

Source: Internet
Author: User
Tags scalar

String is an ordered set of characters, such as "Hello, World", "Albatross". Swift strings are represented by a string type and can also be represented as a collection of Character type values.

string literal

String literals can be used to provide initial values for constants and variables.

" Some string literal value "

Note: Somestring constants are initialized with string literals, so Swift infers that it is a string type.

string literals can contain the following special characters:
    1. Escape special characters, \ \ (backslash), \ t (horizontal tab), \ n (newline character), \ r (carriage return), \ "(double quotation mark), \ ' (single quote).
    2. A single-byte Unicode scalar, written as \xnn, where nn is a two-bit hexadecimal number.
    3. A double-byte Unicode scalar, written as \unnnn, where nnnn is a four-bit hexadecimal number.
    4. A four-byte Unicode scalar, written as \unnnnnnnn, where nnnnnnnn is a eight-bit hexadecimal number.

The following code is an example of the use of various special characters.

The Wisewords constant contains two transfer special characters (double brackets); dollarsign, Blackheart, and Sparklingheart constants demonstrate three different formats of Unicode scalars:

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

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 you can initialize a new string instance:

""               //  var anotheremptystring = string ()  / ///Both strings are empty, and the two are equivalent

The IsEmpty property can be used to determine whether the string is empty:

if Emptystring.isempty {     println ("nothing to see here"//

string Variability

Specify whether the string can be modified by assigning a specific string to a variable (modifying it) or a constant (guaranteeing that it will not be modified):

" Horse "  " and carriage"//"Highlander" "and  another Highlander"//  

string is a value type

Swift's String type is a value type. If you create a new string value, the value is copied when it is passed in a constant, variable assignment operation, or in a function/method. In different cases, a new copy of the existing string value is created.

Character (characters)

Swift's String type represents a collection of character values for a particular sequence. Each character value represents a Unicode character. You can use the for-in loop to iterate through each character in a string:

 for inch " Dog!???? "  {     ///////// /

calculating the number of characters

You can get the number of characters in a string by calling the global countelements function and passing the string as a parameter.

" Koala????, Snail????, Penguin????, dromedary???? " println ("Unusualmenagerie has \ (countelements (Unusualmenagerie)) characters" //

Attention:

1. Different Unicode characters and different representations of the same Unicode characters may require a different amount of memory space to store, so the characters in Swift are represented in a string and do not necessarily occupy the same memory space. As a result, the length of the string has to be computed by iterating through the length of each character in the string. If you are working with a long string, be aware that the countelements function must traverse the characters in the string to accurately calculate the length of the string.  2. It is also important to note that the number of characters returned by Countelements is not always the same as the length property of NSString that contain the same character. The length property of NSString is based on the number of 16-bit code units represented by UTF-16, not Unicode characters. To solve this problem, the length property of NSString is called utf16count when accessed by Swift's string value.

connection strings and characters

The values of strings and characters can be added together with the addition operator (+) and create a new string value:

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 add a string or character to an already existing string variable by using the addition assignment operator (+ =):

"  look over "  + =//"Good Morning"+ =  //

Note: You cannot add a string or character to a character variable that already exists because the character variable can contain only one character.

string Interpolation

String interpolation is a new way to build a string that contains constants, variables, literals, and expressions. Each entry of the string literal that you insert is wrapped in parentheses prefixed with a backslash:

3"\ (multiplier) times 2.5 is \ (Double (multiplier) * 2.5)"//
In The example above, multiplier as \ (multiplier) is inserted into a string literal. When you create a string to perform an interpolation calculation, this placeholder is replaced with the multiplier actual value.  The value of multiplier also acts as part of the subsequent expression in the string. The expression evaluates the value of Double (multiplier) * 2.5 and inserts the result (7.5) into the string. In this example, the expression is written as \ (Double (multiplier) * 2.5) and is included in the string literal. Note:expressions written in parentheses in an interpolated string cannot contain non-escaped double quotation marks (") and backslashes (\), and cannot contain carriage returns or newline characters. Comparing StringsSwift provides three ways to compare the values of strings: strings are equal, prefixes are equal, and suffixes are equal. string Equalityif two strings contain exactly the same characters in the same order, the strings are considered equal:
" We ' re a lot alike, you and I. "  "We ' re a lot alike, you and I. " if quotation = = Samequotation {     println ("These"strings is considered equal
    "//
prefix/suffix equalchecks whether a string has a specific prefix/suffix by calling the Hasprefix/hassuffix method of the string. All two methods need to pass in a string as a parameter and return a Boolean value. Two methods perform a character-by-byte comparison between the base string and the prefix/suffix string.  The following example shows the position of the first two scenes of Shakespeare's play Romeo and Juliet in a string array
Let Romeoandjuliet = [     "Act 1 Scene 1:verona, A Public Place",     "Act 1 Scene 2:capulet ' s mansion",     "Act 1 Scene 3: A 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 to calculate the number of scenes in the first scene of a play using the Romeoandjuliet array:

0  for inch Romeoandjuliet {     if scene.hasprefix ("") {         + +)  Act1scenecount     }} println ("there is \ (Act1scenecount) scenes in Act 1" //

Similarly, the Hassuffix method can be used to calculate the number of scenes that occur in and around Capulet mansions and Lawrence cells.

var mansioncount =0var cellcount=0  forSceneinchRomeoandjuliet {ifScene.hassuffix ("Capulet ' s mansion") {         ++Mansioncount}Else ifScene.hassuffix ("friar Lawrence ' s cell") {         ++Cellcount}} println ("\ (mansioncount) mansion scenes; \ (cellcount) cell scenes") //Prints "6 mansion scenes; 2 cell scenes "

uppercase and lowercase strings

Accesses the uppercase/lowercase version of a string through the uppercasestring and LowerCaseString properties of the string.

" Could do you have help with me, please? "  =//Let whispered =//

Original:http://www.cocoachina.com/ios/20140606/8704.html

2015-03-18

22:25:29

Fourth chapter: Strings and characters

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.