[Swift] Day02: a string in Swift, a string in swiftday02

Source: Internet
Author: User

[Swift] Day02: a string in Swift, a string in swiftday02
Introduction

StringThe string in is of the value type, and the value will be copied during transmission.NSStringIs referenced. We can usefor inTraverse string:

var a : String = “a”for c in “Hello” {    println(c)}

You can usecountElementsCalculate the number of characters in a string:

countElements(“1234567”) // 7

However, note that,countElementsAnd NSStringlengthNot always the same value, becauselengthThe value of the UTF-16 type is used, not the Unicode character. For example, after the emoji expression is added, the result of the UTF-16 calculation is 2, and the Unicode calculation result is 1. See the following example:

var a = “Hello”countElements(a) // 6 - Unicodea.utf16Count     // 7 - UTF16

You can use utf8 to get the UTF-8 representation. Similarly, you can use utf16 to get the representation of the UTF-16:

var b = “Hello”// 72 101 108 108 111 240 159 144 182for c in b.utf8 {    println(c)}// 72 101 108 108 111 55357 56374for c in b.utf16 {    println(c)}

To obtain the Unicode scalar, you can useunicodeScalarsTo obtain:

// 68 111 103 33 128054”for scalar in b.unicodeScalars {    print(“\(scalar.value) “)}
Substring

We cannot directly usestr[0...4]To intercept the substring, because the StringSubscriptMust beString.IndexOf:

subscript(i: String.Index) -> Character { get }subscript(subRange: Range<String.Index>) -> String { get }

To obtain the SubString, You need:

let digits = “0123456789”let position = 3let index = advance(digits.startIndex, position)let character = digits[index] // -> “3”

Or usesubstringWithRangeMethod:

var str = “abcdefg”str.substringWithRange(Range<String.Index>(start: advance(str.startIndex,2), end: str.endIndex))

Where,advance(i, n)Equivalenti++n, Only oneForwardIndexTypeCan ReturniNextn. For exampleadvance(1, 2)The returned result is1+2That is, 3.

We can useExtensionTo add the subscript of the integer type to the String:

var digits = “12345678901234567890”extension String{    subscript(integerIndex: Int) -> Character        {            let index = advance(startIndex, integerIndex)            return self[index]    }    subscript(integerRange: Range<Int>) -> String        {            let start = advance(startIndex, integerRange.startIndex)            let end = advance(startIndex, integerRange.endIndex)            let range = start..<end            return self[range]    }}digits[5]     // works nowdigits[4…6] // works now

AvailablerangeOfString()To determine whether a substring is included:

var myString = “Swift is really easy!”if myString.rangeOfString(“easy”) != nil {    println(“Exists!”)}
Splicing

It is common to splice values in an array into strings. We can use traversal to splice all elements:

let animals = [“cat”, “dog”, “turtle”, “swift”, “elephant”]var result: String = “”for animal in animals {    if countElements(result) > 0 {        result += “,”    }    result += animal}result  // “cat,dog,turtle,swift,elephant”

Of course, there are also simpler methods,joinFunction:

println(“a list of animals: ” + “,”.join(animals))

AvailablemapAdd a list tag to each element:

println(“\n”.join(animals.map({ “- ” + $0})))

CapitalizedString can be used to uppercase the first letter of a string:

let capitalizedAnimals = animals.map({ $0.capitalizedString })println(“\n”.join(capitalizedAnimals.map({ “- ” + $0})))

You can usesorted()Method to sort the elements in the group:

let sortedAnimals = animals.sorted({ (first, second) -> Bool in    return first < second})println(“\n”.join(sortedAnimals.map({ “- ” + $0})))

You can use custom operators to implement strings.*nThe effect is like3*5=15In this way:

func *(string: String, scalar: Int) -> String {    let array = Array(count: scalar, repeatedValue: string)     return “”.join(array)}println(“cat ” * 3 + “dog ” * 2)// cat cat cat dog dog
Decomposition

Based onFoundation, We can usecomponentsSeparatedByStringBreak down strings into Arrays:

import Foundationvar myString = “Berlin, Paris, New York, San Francisco”var myArray = myString.componentsSeparatedByString(“,”)//Returns an array with the following values:  [“Berlin”, ” Paris”, ” New York”, ” San Francisco”]

If you want to break down multiple characters, you need to use another method:

import Foundationvar myString = “One-Two-Three-1 2 3”var array : [String] = myString.componentsSeparatedByCharactersInSet(NSCharacterSet (charactersInString: “- “))//Returns [“One”, “Two”, “Three”, “1”, “2”, “3”]

If you do not wantFoundationFor decomposition, you can use global functionssplit():

var str = “Today is so hot”let arr = split(str, { $0 == ” “}, maxSplit: Int.max, allowEmptySlices: false)println(arr) // [Today, is, so, hot]
Summary

In Swift,StringAndNSStringIt is automatically converted. Although String is very powerful, it is not easy to use. You can refer to the ExSwift project on the Internet. The String. swift is a good complement to some frequently-used String content that Apple does not provide.

References
  • Playing with Strings
  • String reference guide for Swift
  • Swift version of componentsSeparatedByString
  • Strings in Swift

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.