在 Swift 中重新排序字符串字符

问题描述 投票:0回答:3

所以,假设我有一个字符串:“abc”,我想更改每个字符位置,以便我可以有“cab”,然后是“bca”。我希望索引 0 处的字符移动到 1,索引 1 处的字符移动到 2,索引 2 处的字符移动到 0。

我在 Swift 中有什么可以做到这一点?另外,假设我用的是数字而不是字母。有没有更简单的方法来处理整数?

string swift indexing integer character
3个回答
1
投票

斯威夫特2:

extension RangeReplaceableCollectionType where Index : BidirectionalIndexType {
  mutating func cycleAround() {
    insert(removeLast(&self), atIndex: startIndex)
  }
}

var ar = [1, 2, 3, 4]

ar.cycleAround() // [4, 1, 2, 3]

var letts = "abc".characters
letts.cycleAround()
String(letts) // "cab"

斯威夫特1:

func cycleAround<C : RangeReplaceableCollectionType where C.Index : BidirectionalIndexType>(inout col: C) {
  col.insert(removeLast(&col), atIndex: col.startIndex)
}

var word = "abc"

cycleAround(&word) // "cab"

0
投票

Swift Algorithms 包中 有一个

rotate
命令

import Algorithms

let string = "abcde"
var stringArray = Array(string)
for _ in 0..<stringArray.count {
    stringArray.rotate(toStartAt: 1)
    print(String(stringArray))
}

结果:

bcdea
cdeab
deabc
eabcd
abcde

0
投票

斯威夫特5.7.2

我遇到一个问题,需要标准化不同来源的库存编号。一些源会将字母字符放置在单元代码的数字部分之前,而其他源会将字母字符附加到单元代码的数字部分的末尾。我需要的格式是字符必须出现在数字之前。

我首先必须将字符串分解为单独的字符串元素,因为单元代码使用破折号,但一旦完成,就非常简单了。

方法:

func swapEndLetter(string: String) -> String {
    var string = string
    guard let letter = string.last?.isLetter else { return string }
    if letter {
        return "\(string.remove(at: string.index(before: string.endIndex)))\(string)"
    }
    return string
}

用途:

var unitCode = "unit-code-a1102"
var split = unitCode.components(separatedBy: "-")
split[split.count-1] = swapEndLetter(string: String(split[split.count-1]))
unitCode = split.joined(separator: "-")
© www.soinside.com 2019 - 2024. All rights reserved.