如何获取方法链中字符串的第一个或最后几个字符? [英] How to I get the first or last few characters of a string in a method chain?
本文介绍了如何获取方法链中字符串的第一个或最后几个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我使用函数式方法链进行字符串操作,则不能使用 用于获取第一个或最后几个字符的常用机制:我无法访问对当前字符串的引用,因此我无法计算索引.
If I use functional-style method chains for string manipulation, I can not use the usual machinery for getting the first or last few characters: I do not have access to a reference to the current string, so I can not compute indices.
示例:
[some, nasty, objects]
.map( { $0.asHex } )
.joined()
.<first 100>
.uppercased()
+ "..."
用于截断的调试输出.
那么我如何实现
,或者我必须打破链条?
So how to I implement <first 100>
, or do I have to break the chain?
推荐答案
我不知道有任何 API 可以做到这一点.幸运的是,编写我们自己的代码是一项简单的练习:
I don't know of any API that does this. Fortunately, writing our own is an easy exercise:
extension String {
func taking(first: Int) -> String {
if first <= 0 {
return ""
} else if let to = self.index(self.startIndex,
offsetBy: first,
limitedBy: self.endIndex) {
return self.substring(to: to)
} else {
return self
}
}
}
从最后开始是类似的.
在此处查找完整代码(包括变体)和测试.
Find full code (including variants) and tests here.
这篇关于如何获取方法链中字符串的第一个或最后几个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文