Swift3.0语言教程获得一个公共的前缀

Swift3.0语言教程获得一个公共的前缀

Swift3.0语言教程获得一个公共的前缀,当在一个程序中有多个字符串时,我们需要判断是否有两个字符串有公共的前缀时,是很困难的。在NSString中的commonPrefix(with:options:)方法为开发者解决了这一问题,它可以获取在两个字符串中公共的前缀,其语言形式如下:

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

其中,str用来指定一个比较的字符串。Mask用来指定比较选项。

【示例1-21】以下将获取两个字符串公共的前缀。

import Foundation

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

//获取公共前缀

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

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

运行结果如下:

Hello,

 

注意:在程序中字符串a和字符串"123456"是没有公共前缀的,所以就会输出空,也就是运行结果中看到的内容Swift3.0语言教程获得一个公共的前缀

原文地址:https://www.cnblogs.com/daxueba-ITdaren/p/6029563.html