我从这个开始:
我想使用特定的字符串格式化句子
let formatter = "%@ is friend of %@"
let you = "you"
let me = "me"
let reply = String(format: formatter, you, me)
这很好。打印您是我的朋友
现在我要与此相反,即
如果我有这样的字符串,您是我的朋友,我想使用格式化程序"%@ is friend of %@"
从此字符串中获取值,以便它给出如下值数组: “你”“我”)
任何建议都是有帮助的
答案 0 :(得分:1)
这有点复杂,但是您可以尝试使用正则表达式。
let reply = "You is friend of me"
let format = "%@ is friend of %@"
var result: [String] = []
let pattern = NSRegularExpression.escapedPattern(for: format)
.replacingOccurrences(of: "%@", with: "(.*)")
let regex = try! NSRegularExpression(pattern: "^" + pattern + "$")
if let match = regex.firstMatch(in: reply, range: NSRange(0..<reply.utf16.count)), match.numberOfRanges > 0 {
for i in 1..<match.numberOfRanges {
result.append(String(reply[Range(match.range(at: i), in: reply)!]))
}
} else {
print("format does not match")
}
print(result) //->["You", "me"]
请尝试使用此代码获取其他一些格式,以及使用该格式生成的结果文本。
答案 1 :(得分:-1)
您可以尝试
let str = yourString.replacingOccurrences(of: " is friend of ", with: ",")
let arr = str.components(separatedBy: ",")
print("first:- \(arr[0]) , second:- \(arr[1])")