Swift3 0語言教程字串與檔案的資料轉換

2021-09-08 22:39:29 字數 1816 閱讀 6389

swift3.0語言教程字串與檔案的資料轉換,如果想要對字串中的字元進行永久儲存,可以將字串中的字元寫入到檔案中。當然,開發者也可以將寫入的內容進行讀取,並轉換為字串。首先我們來看如何將字串中的字元寫入到檔案中,要想實現此功能,需要使用到nsstring中的write(tofile:atomically:encoding:)方法,其語法形式如下:

func write(tofile path: string, atomically useauxiliaryfile: bool, encoding enc: uint) throws

其中,引數說明如下:

【示例1-100】以下將字串中的字元寫入到file空檔案中。

import foundation

var str=nsstring(string:"all things are difficult before they are easy.")

var path="/users/mac/desktop/file"

//寫入

docatch

執行效果如圖1.1所示。

圖1.1  執行效果

在此程式中我們提到了空檔案,此檔案的建立需要實現以下幾步:

(1)在xcode的選單中選擇「flie|new|file…」命令,彈出choose a template for your new file:對話方塊,如圖1.2所示。

圖1.2  choose a template for your new file:對話方塊

(2)選擇macos的other中的empty模板,單擊next按鈕,彈出檔案儲存位置對話方塊,如圖1.3所示。

圖1.3  檔案儲存位置對話方塊

(3)輸入檔名稱,選擇好檔案儲存的位置後,單擊create按鈕,此時乙個file空檔案就建立好了,如圖1.4所示。

圖1.4  file檔案

通過nsstring可以將字串中的字元寫入到指定檔案中,還可以將檔案中的內容讀取出來。讀取檔案內容需要使用到nsstring中的的init(contentsoffile:encoding:)方法,其語法形式如下:

convenience init(contentsoffile path: string, encoding enc: uint) throws

其中,path用來指定需要讀取檔案的路徑,enc用來指定編碼格式。

【示例1-101】以下將讀取檔案file中的內容。

import foundation

var path="/users/mac/desktop/file"

var str:nsstring?=nil

//讀取檔案內容

docatch

print(str!)

執行結果如下:

all things are difficult before they are easy.

swift3.0語言教程字串與檔案的資料轉換

Swift3 0語言教程組合字串

其中,astring用來指定乙個字串。import foundation var a nsstring string hello,print 組合前 a 組合字串 print 組合後 b 執行結果如下 組合前 hello,組合後 hello,world 2 padding tolength with...

Swift3 0語言教程使用URL字串

swift3.0語言教程使用url字串,和路徑一樣,url其實也是字串,我們可以將這些字串稱為url字串。本小節將講解url字串的使用。1.編碼 現在的網路存在很多的洩漏資訊的危險,為了解決這一危險,url字串提供了編碼的的方式,在nsstring中開發者可以使用addingpercentencod...

Swift3 0語言教程使用URL字串

swift3.0語言教程使用url字串,和路徑一樣,url其實也是字串,我們可以將這些字串稱為url字串。本小節將講解url字串的使用。1.編碼 現在的網路存在很多的洩漏資訊的危險,為了解決這一危險,url字串提供了編碼的的方式,在nsstring中開發者可以使用addingpercentencod...