请问使用Swift的字符串中子字符串的索引

使用Swift的字符串中子字符串的索引

我习惯在JavaScript中这样做:

var domains = "abcde".substring(0, "abcde".indexOf("cd")) // Returns "ab"

Swift没有这个功能,如何做类似的事情?


森林海
浏览 425回答 3
3回答

HUH函数

测试Swift 4.2 / 4.1 / 4.0 / 3.0使用String[Range<String.Index>]下标,您可以获得子字符串。您需要启动索引和最后一个索引来创建范围,您可以按照以下方式执行此操作let&nbsp;str&nbsp;=&nbsp;"abcde"if&nbsp;let&nbsp;range&nbsp;=&nbsp;str.range(of:&nbsp;"cd")&nbsp;{ &nbsp;&nbsp;let&nbsp;substring&nbsp;=&nbsp;str[..<range.lowerBound]&nbsp;//&nbsp;or&nbsp;str[str.startIndex..<range.lowerBound]&nbsp;&nbsp;print(substring)&nbsp;&nbsp;//&nbsp;Prints&nbsp;ab}else&nbsp;{ &nbsp;&nbsp;print("String&nbsp;not&nbsp;present")}如果没有为此运算符定义起始索引..<,则采用起始索引。您也可以使用str[str.startIndex..<range.lowerBound]而不是str[..<range.lowerBound]

长风秋雁

在Swift 4中:获取字符串中的字符索引:let str = "abcdefghabcd"if let index = str.index(of: "b") {&nbsp; &nbsp;print(index) // Index(_compoundOffset: 4, _cache: Swift.String.Index._Cache.character(1))}使用Swift 4从String创建SubString(前缀和后缀):let str : String = "ilike"for i in 0...str.count {&nbsp; &nbsp; let index = str.index(str.startIndex, offsetBy: i) // String.Index&nbsp; &nbsp; let prefix = str[..<index] // String.SubSequence&nbsp; &nbsp; let suffix = str[index...] // String.SubSequence&nbsp; &nbsp; print("prefix \(prefix), suffix : \(suffix)")}产量prefix , suffix : ilikeprefix i, suffix : likeprefix il, suffix : ikeprefix ili, suffix : keprefix ilik, suffix : eprefix ilike, suffix :&nbsp;如果要生成2个索引之间的子字符串,请使用:let substring1 = string[startIndex...endIndex] // including endIndexlet subString2 = string[startIndex..<endIndex] // excluding endIndex
打开App,查看更多内容
随时随地看视频慕课网APP