Swift Learning-04--strings and characters

Source: Internet
Author: User
Tags scalar

Strings and characters

A string is an ordered collection of Character (character) types of values, through a collection of string types

Swift's string and Character types provide a fast and Unicode-compatible way for your code to use, creating and manipulating strings similar to those in C, lightweight and read

The string join operation simply connects two strings via the + symbol

As with other values in swift, you can change the value of a string, depending on whether it is defined as a constant or a variable

Attention:

Swift's string type is seamlessly interfaced to the foundation NSString class, and the foundation can also extend the string to expose the method defined in NSString, which means that if you tune in string With these nsstring methods, no conversion is necessary.

var ss = "Aaaaaaa"

Let BB = ss + "BBBBBB"

Print (BB)

string literal

string literal roommate double quotation mark ("") wrapped with a fixed-order text character set

String literals can provide initial values for constants or variables

Initializing an empty string

To 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 emptystring = ""//empty string literal

var antheremptystring = String ()//initialization method

You can determine whether the string is empty by checking the IsEmpty property of its type Bool

If emptystring.isempty{

Print ("Nothing to see here")

}

String variability

You can modify a specific string by assigning it to a variable, or assign it to a constant to ensure that it is not modified

Attention:

In Objective-c and Cocoa, you need to specify whether a string can be modified by selecting two different classes (NSString and nsmutablestring)

Using characters

You can use the for-in loop to iterate through the characters property in a string to get the value of each character;

For Charcater in "Dog!??". Characters {

Print (Charcater)

}

In addition, you can create a separate character constant or variable by indicating a Character type and copying it with the character literal.

Let Exclamationmark:character = "!"

A string can be initialized by passing an array of value type Character as an argument.

Let catcahracter: [Character] = ["C", "a", "T", "!", "??"]

Let catstring = String (catcahracter)

Print (catstring)

Connection strings and characters

Strings can be added together (or concatenated) by adding operators (+) to create a new string

Let string1 = "Hello"

Let string2 = "the World"

var welcome = string1 + string2

You can also add a string to an already existing string by adding an assignment operator (+ =)

var instryction = "Look over"

Instryction + = string2

You can also use the Append () method to add a character to the tail of a string variable

Let Exclamationmark:character = "!"

Welcome.append (Exclamationmark)

Welcome.append (string2)

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 way to construct a new string that can contain constants. variables, literals, and expressions

Each entry of the string literal you insert is enclosed in parentheses prefixed with a backslash

Attention:

An expression written in parentheses in an interpolated string cannot contain a non-escaped backslash (\) and cannot contain a carriage return or newline character, but an interpolated string can contain other literals

Unicode

Swift's string type is based on Unicode scalars.

A Unicode scalar is a unique 21-bit number that corresponds to a character or modifier.

Special characters for string literals

String literals can contain the following special characters

Escape character: (null character), \ \ (backslash), \ n (newline character), \ r (carriage return)

\ "(double quotes), \ ' (single quote), Unicode scalar, written \u{n} (u lowercase) where n is any one to eight hexadecimal digits and available Unicode bit codes

Scalable glyph Clusters

Each swift Character type represents an extensible Glyph group, an extensible Glyph group is one or more ordered permutations of Unicode scalars that produce human-readable characters

Calculating the number of characters

If you want to get the number of Character values in a string, you can use the Count property of the Character property of the string

var word = "Cafe"

Print ("The number of characters in \ (word) is \ (Word.characters.count)")

Print output "The number of characters in Cafe is 4"

Accessing and modifying strings

You can access and modify it through the properties and methods of the string, or you can do it with the following banner.

String index

Each string value has an associated index type, String.index, which corresponds to the position of each character in a string.

Different strings may occupy a different amount of memory space, so to know the location of the character, you must traverse each Unicode scalar from the beginning of the string to the end, so that Swift's string cannot be indexed by an integer (Interger)

Use the StartIndex property to get the index of the first character of a string, using the EndIndex property to get the index of the last position of the final character, so that EndIndex cannot be used as a string for a valid If the string is an empty string, StartIndex and EndIndex are equal

By calling the index of string (before:) or index (after:) method, you can immediately get a previous or subsequent index, and you can also call index (_:offsetby:). method to get the index of the corresponding offset, which avoids multiple calls to index (before:) or index (after:) Method

Let greenting = "Guten tag!"

Print (Greenting[greenting.startindex])

Greenting[greenting.index (Before:greenting.endIndex)]

Greenting[greenting.index (After:greenting.startIndex)]

Let index = Greenting.index (Greenting.startindex, Offsetby:7)

Greenting[index]

Using the indices property of the character property creates a range (range) of all indexes to be used to access a single character in a string

For index in Greenting.characters.indices {

Print ("\ (Greenting[index])")

}

Note: You can use the startindex and EndIndex properties or (Index:before), index (after:) and index: (_:offsetby:) Method in any of the seven types that determine and follow the collection protocol, as shown above is used in String, you can also use in array, dictionary and set

Inserting and deleting

Call Insert (_:at:) The Contentsof:at method can insert a character at the specified index of a string, calling Insert (:) method to insert a segment string at the specified index of a string

var welcomestr = "Hello"

Welcomestr.insert ("!", At:welcomeStr.endIndex)

Welcomestr.insert (contentsof: "There". Characters, At:welcomeStr.index (Before:welcomeStr.endIndex))

Call Remove (at:) Method can delete a character at the specified index of a string,

Call Removesubrange (_:) method to delete a substring at the specified index of a string

Welcomestr.remove (At:welcomeStr.index (Before:welcomeStr.endIndex))

Let Renge = Welcomestr.index (Welcomestr.endindex, Offsetby:-6). <welcomestr.endindex

Welcomestr.removesubrange (Renge)

Note: You can use Insert (_:at:), insert (contentsof:at:), remove (at:) And Removesubrange (_:) Method in any of the types that follow and confirm the Rangereplaceablecollection protocol, as shown above is used in string, you can also use in Array, dictionary and set

Comparing strings

Swift provides three ways to compare text values, string characters are equal, prefixes are equal and suffixes are equal

string/character equality

The string/character can use the equals operator (= =), and the Not equal operator (! =)

Let quotation = "we ' re a lot alike, you and I."

Let samequotation = "we ' re a lot alike, you and I."

If quotation = = Samequotation {

Print ("There strings is considered equal")

}

prefix/suffix equal

By calling the string Hasprefix (_:)/Hassuffix (_:) method to check whether a string has a specific prefix/suffix, two methods accept a string parameter, and return a Boolean value

The Unicode representation of a string

When a Unicode string is written into a text file or other store, the Unicode scalar in the string is encoded in several encoding formats defined by Unicode (encodeing forms), and the small block encoding in each string is called the code unit NITs), these include UTF-8 encoded appropriately (coded strings are 8-bit code units), UTF-16, UTF-32

Swift provides several different ways to access the Unicode representation of a string

You can use for-in to traverse strings to access each cahracer value in a Unicode-extensible character cluster

UTF-8 says

You can use the UTF-8 property of String to access his UTF-8 representation

Swift Learning-04--strings and characters

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.