Swift3.0語言教程得到一個公共的前綴

Swift3.0語言教程得到一個公共的前綴

Swift3.0語言教程得到一個公共的前綴,當在一個程序中有多個字符串時,咱們須要判斷是否有兩個字符串有公共的前綴時,是很困難的。在NSString中的commonPrefix(with:options:)方法爲開發者解決了這一問題,它能夠獲取在兩個字符串中公共的前綴,其語言形式以下:spa

func commonPrefix(with str: String, options mask: NSString.CompareOptions = []) -> String教程

其中,str用來指定一個比較的字符串。Mask用來指定比較選項。開發

【示例1-21】如下將獲取兩個字符串公共的前綴。字符串

import Foundationstring

var a=NSString(string: "Hello,World")it

//獲取公共前綴io

print(a.commonPrefix(with: "Hello,Swift", options: NSString.CompareOptions.anchored))import

print(a.commonPrefix(with: "123456", options: NSString.CompareOptions.anchored))程序

運行結果以下:方法

Hello,

 

注意:在程序中字符串a和字符串"123456"是沒有公共前綴的,因此就會輸出空,也就是運行結果中看到的內容Swift3.0語言教程得到一個公共的前綴。

相關文章
相關標籤/搜索