目标:具有内置分隔符的字符串应分为int和另一个字符串。如果分隔符序列'###'出现不止一次,则字符串应始终拼接在最后一个'###'。
是否有类似string.lastIndexOf(“###”)的运算符,就像在C#中一样?
这就是我的解析器的样子:
func parseTuple(from string: String) -> (String, Int)? {
let parsedString = string.components(separatedBy: "###")
if let tupleString = String(parsedString[0]), let tupleInt = Int(parsedString[1]) {
return (tupleString, tupleInt)
} else {
return nil
}
}
答案 0 :(得分:4)
String
的{{3}}方法有.backwards
个选项
找到最后一次出现的字符串。
然后substring(to:)
和substring(from:)
可以与。{1}}和func parseTuple(from string: String) -> (String, Int)? {
if let theRange = string.range(of: "###", options: .backwards),
let i = Int(string.substring(from: theRange.upperBound)) {
return (string.substring(to: theRange.lowerBound), i)
} else {
return nil
}
}
一起使用
该范围的下限/上限以提取字符串的部分
在分隔符之前/之后:
if let tuple = parseTuple(from: "Connect###Four###Player###7") {
print(tuple)
// ("Connect###Four###Player", 7)
}
示例:
func parseTuple(from string: String) -> (String, Int)? {
if let theRange = string.range(of: "###", options: .backwards),
let i = Int(string[theRange.upperBound...]) {
return (String(string[...theRange.lowerBound]), i)
} else {
return nil
}
}
Swift 4更新:
@Document
public class Artikal {
public enum StatusZapisa {AKTIVAN, ARHIVIRAN}
@Id
private int sifra;
private String naziv;
@DBRef
private KategorijaArtikla kategorija;
private float cena;
private int brojnoStanje;
private Date datumKreiranjaZapisa;
private boolean daLiPopunitiZalihe;
private StatusZapisa statusZapisa;
private int minimalnoStanje;
答案 1 :(得分:1)
let input = "Connect###Four###Player###7"
let seperator = "###"
// split components
var components = input.components(separatedBy: seperator)
// remove the last component ...
components = Array(components.dropLast())
// ... and re-join the remaining ones
let output = components.joined(separator: seperator)
print(output)
打印:
Connect###Four###Player