我有一个包含二进制数字的字符串。如何将其分成数字对?
假设字符串是:
let x = "11231245"
我想添加一个分隔符,例如":" (每个2个字符后)(即冒号)。
我希望输出为:
"11:23:12:45"
我怎么能在Swift中做到这一点?
答案 0 :(得分:48)
Swift 4.2•Xcode 10
extension Collection {
var pairs: [SubSequence] {
var startIndex = self.startIndex
let count = self.count
let n = count/2 + count % 2
return (0..<n).map { _ in
let endIndex = index(startIndex, offsetBy: 2, limitedBy: self.endIndex) ?? self.endIndex
defer { startIndex = endIndex }
return self[startIndex..<endIndex]
}
}
}
extension StringProtocol where Self: RangeReplaceableCollection {
mutating func insert(separator: Self, every n: Int) {
for index in indices.reversed() where index != startIndex &&
distance(from: startIndex, to: index) % n == 0 {
insert(contentsOf: separator, at: index)
}
}
func inserting(separator: Self, every n: Int) -> Self {
var string = self
string.insert(separator: separator, every: n)
return string
}
}
<强>测试强>
let str = "112312451"
let final = str.pairs.joined(separator: ":")
print(final) // "11:23:12:45:1"
let final2 = str.inserting(separator: ":", every: 2)
print(final2) // "11:23:12:45:1\n"
var str2 = "112312451"
str2.insert(separator: ":", every: 2)
print(str2) // "11:23:12:45:1\n"
var str3 = "112312451"
str3.insert(separator: ":", every: 3)
print(str3) // "112:312:451\n"
var str4 = "112312451"
str4.insert(separator: ":", every: 4)
print(str4) // "1123:1245:1\n"
答案 1 :(得分:14)
我会选择这个紧凑的解决方案(在Swift 4中):
let s = "11231245"
let r = String(s.enumerated().map { $0 > 0 && $0 % 2 == 0 ? [":", $1] : [$1]}.joined())
你可以对stride和分隔符进行扩展和参数化,以便你可以将它用于你想要的每个值(在我的例子中,我用它来转储32位空间操作的十六进制数据):
extension String {
func separate(every stride: Int = 4, with separator: Character = " ") -> String {
return String(enumerated().map { $0 > 0 && $0 % stride == 0 ? [separator, $1] : [$1]}.joined())
}
}
在您的情况下,这会得到以下结果:
let x = "11231245"
print (x.separate(every:2, with: ":")
$ 11:23:12:45
答案 2 :(得分:9)
简短而简单,如果需要,可添加let
或两个
extension String {
func separate(every: Int, with separator: String) -> String {
return String(stride(from: 0, to: Array(self).count, by: every).map {
Array(Array(self)[$0..<min($0 + every, Array(self).count)])
}.joined(separator: separator))
}
}
let a = "separatemepleaseandthankyou".separate(every: 4, with: " ")
a
是
分离mepl ease andt hank you
答案 3 :(得分:7)
我对该代码的尝试将是:
func insert(seperator: String, afterEveryXChars: Int, intoString: String) -> String {
var output = ""
intoString.characters.enumerate().forEach { index, c in
if index % afterEveryXChars == 0 && index > 0 {
output += seperator
}
output.append(c)
}
return output
}
insert(":", afterEveryXChars: 2, intoString: "11231245")
哪个输出
11:23:12:45
答案 4 :(得分:7)
let y = String(
x.characters.enumerate().map() {
$0.index % 2 == 0 ? [$0.element] : [$0.element, ":"]
}.flatten()
)
答案 5 :(得分:5)
我的代码在swift 4
foreach (var k in DateList)
{
while (Calendar.BlackoutDates.Any(bd => bd.Start.Date == k.Date))
{
Calendar.BlackoutDates.Remove(Calendar.BlackoutDates.FirstOrDefault(bd => bd.Start.Date == k.Date));
}
}
输出11:23:12:45
答案 6 :(得分:5)
Swift 5.3
/// Adds a separator at every N characters
/// - Parameters:
/// - separator: the String value to be inserted, to separate the groups. Default is " " - one space.
/// - stride: the number of characters in the group, before a separator is inserted. Default is 4.
/// - Returns: Returns a String which includes a `separator` String at every `stride` number of characters.
func separated(by separator: String = " ", stride: Int = 4) -> String {
return enumerated().map { $0.isMultiple(of: stride) && ($0 != 0) ? "\(separator)\($1)" : String($1) }.joined()
}
答案 7 :(得分:1)
Swift 4.2.1-Xcode 10.1
extension String {
func insertSeparator(_ separatorString: String, atEvery n: Int) -> String {
guard 0 < n else { return self }
return self.enumerated().map({String($0.element) + (($0.offset != self.count - 1 && $0.offset % n == n - 1) ? "\(separatorString)" : "")}).joined()
}
mutating func insertedSeparator(_ separatorString: String, atEvery n: Int) {
self = insertSeparator(separatorString, atEvery: n)
}
}
用法
let testString = "11231245"
let test1 = testString.insertSeparator(":", atEvery: 2)
print(test1) // 11:23:12:45
var test2 = testString
test2.insertedSeparator(",", atEvery: 3)
print(test2) // 112,312,45
答案 8 :(得分:1)
用于插入分隔符的简单一行代码(Swift 4.2):-
let testString = "123456789"
let ansTest = testString.enumerated().compactMap({ ($0 > 0) && ($0 % 2 == 0) ? ":\($1)" : "\($1)" }).joined() ?? ""
print(ansTest) // 12:34:56:78:9
答案 9 :(得分:0)
extension String{
func separate(every: Int) -> [String] {
return stride(from: 0, to: count, by: every).map {
let ix0 = index(startIndex, offsetBy: $0);
let ix1 = index(after:ix0);
if ix1 < endIndex {
return String(self[ix0...ix1]);
}else{
return String(self[ix0..<endIndex]);
}
}
}
///或O(1)实现(不计数)
func separate(every: Int) -> [String] {
var parts:[String] = [];
var ix1 = startIndex;
while ix1 < endIndex {
let ix0 = ix1;
var n = 0;
while ix1 < endIndex && n < every {
ix1 = index(after: ix1);
n += 1;
}
parts.append(String(self[ix0..<ix1]));
}
return parts;
}
"asdf234sdf".separate(every: 2).joined(separator: ":");
答案 10 :(得分:0)
一个简单的String扩展名,它不需要原始字符串是步长(增量)的倍数:
extension String {
func inserted(_ newElement: Character,atEach increment:Int)->String {
var newStr = self
for indx in stride(from: increment, to: newStr.count, by: increment).reversed() {
let index = String.Index(encodedOffset: indx)
newStr.insert(newElement, at: index)
}
return newStr
}
}
答案 11 :(得分:0)
我来这里不晚,但是我喜欢这样使用正则表达式:
extension String {
func separating(every: Int, separator: String) -> String {
let regex = #"(.{\#(every)})(?=.)"#
return self.replacingOccurrences(of: regex, with: "$1\(separator)", options: [.regularExpression])
}
}
"111222333".separating(every: 3, separator: " ")
输出:
"111 222 333"