【问题标题】:Split a Swift string from part a to part b?将 Swift 字符串从 a 部分拆分到 b 部分?
【发布时间】:2019-01-12 22:15:18
【问题描述】:

我正在寻找一种将整个文本分成 2 个或更多部分的方法。因此,如果我有以下代码:

var Text = "INGREDIENTS\n Milk \nSugar \nSoda \nINFORMATIONS \nYou need to add more sugar"

var SplitPart1 = ""
var SplitPart2 = ""

如何在“SplitPart1”和“SplitPart2”中从“INGREDIENTS”到“INFORMATIONS”获取零件? 最后,我需要这两个字符串:

SplitPart1:成分\n牛奶\n糖\n苏打水\n

SplitPart2: INFORMATIONS \n你需要添加更多的糖

【问题讨论】:

标签: swift string substring


【解决方案1】:

我快速搜索了一下,找到了Index of a substring in a string with Swift,但是,直接使用的答案不是很明显,所以我写了这个快速测试......

let text = "INGREDIENTS\n Milk \nSugar \nSoda \nINFORMATIONS \nYou need to add more sugar"
if let range = text.range(of: "INFORMATIONS") {

    let start = text[..<range.lowerBound]
    let end = text[range.lowerBound...]

    print("start:", start)
    print("end:", end)
}

这会产生...

//    start: INGREDIENTS
//    Milk
//    Sugar
//    Soda
//
//    end: INFORMATIONS
//    You need to add more sugar

【讨论】:

  • 哇,这速度很快,而且效果很好。非常感谢! :)
  • 哦,我还有一个关于这个的问题......如果我需要第三部分,我该如何分开第三部分?
  • 可能将第二部分拆分为单独的步骤,但您也可以从初始文本中获取文本范围
【解决方案2】:

前提是你只得到了这种格式的字符串并且你不能改变它。下面是一些尝试使其动态化。您将获得可用于填充数据的拆分数组。

var Text = "INGREDIENTS\n Milk \nSugar \nSoda \nINFORMATIONS \nYou need to add more sugar \nSOMETHINGELSE \n Deliver soon"

//1) Define the Seperator Keys
let SeperatorKey: Set = ["INGREDIENTS", "INFORMATIONS", "SOMETHINGELSE"]

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        splitString(text: Text)
    }

    //2.This method will split the strings based on SeperatorKey
    func splitString(text: String){
        let textArray = text.split(separator: "\n")

        let (count, indexes) = getNumberAndIndexOfCategories(textArray: textArray)

        for i in 0..<count {
            let startIndex = indexes[i]
            let endIndex = i == (count - 1) ? textArray.count : indexes[i+1]
            let subTextArray = textArray[startIndex..<endIndex]

            print("SubText = \(subTextArray)")
        }
    }

    func getNumberAndIndexOfCategories(textArray: [String.SubSequence]) -> (Int, [Int]){
        var count = 0
        var indexes: [Int] = []
        for (index, string) in textArray.enumerated() {
            let trimmedString = string.trimmingCharacters(in: .whitespaces)
            if SeperatorKey.contains(String(trimmedString)){
                count = count + 1
                indexes.append(index)
            }
        }
        return (count, indexes)
    }
}

【讨论】:

    【解决方案3】:

    这是拆分和加入字符串的一般方法:

        extension String{
       func split(_ separatingString: String) -> [String]{
        return   components(separatedBy: separatingString).reduce(into: [], { (result, next) in
            result.isEmpty  ?  result.append(next)  : result.append(separatingString + next)
        })}}
    
     var Text = "INGREDIENTS\n Milk \nSugar \nSoda \nINFORMATIONS \nYou need to add more sugar"
    
     print(Text.split("INFORMATIONS"))
    

    对于具有更多关键字的扩展。

    扩展可能是这样的:

     extension String{
    func split(_ separatingString: String) -> [String]{
            let array =  components(separatedBy: separatingString)
        return  array.first!.isEmpty  ?  array.dropFirst().map{separatingString + $0} :
            [array.first!] + array.dropFirst().map{separatingString + $0}
    }
    
    func splitArray(_ array :[String]) -> [String]{
        return   array.reduce( [self]) { (result, next) -> [String] in
            return  [String](result.compactMap{$0.split(next)}.joined())
         }
    }
    }
    
    
    
    
    
    
    var Text = "INGREDIENTS\n Milk \nSugar \nSoda \nINFORMATIONS \nYou need to add more sugar"
    
    
    print(Text.splitArray(["INFORMATIONS", "add", "Milk", "INGREDIENTS", "suger"]))
    
    //["INGREDIENTS\n ", "Milk \nSugar \nSoda \n", "INFORMATIONS \nYou need to ", "add more sugar"]
    
    
      print(Text.splitArray(["INFORMATIONS", "INGREDIENTS"]))
      print(Text.splitArray(["INGREDIENTS", "INFORMATIONS"]))
    
     // ["INGREDIENTS\n Milk \nSugar \nSoda \n", "INFORMATIONS \nYou need to add more sugar"]
     // ["INGREDIENTS\n Milk \nSugar \nSoda \n", "INFORMATIONS \nYou need to add more sugar"]
    

    这不是最快的方法,但逻辑清晰。关键字不需要在这里排序。如果你知道顺序,这种方法比序列尾递归要慢。

    【讨论】:

    • uuhhhh 创意缩进是怎么回事?
    • 另外,你可以直接使用joined(separator:),而不是自己用reduce实现。它更清晰。
    • 而且你不应该检查if result.count == 0检查它是否为空result.isEmpty
    • @Alexander,结果是一个数组而不是一个字符串。
    • 要检查集合是否为空,请使用其 isEmpty 属性,而不是将 count 与零进行比较。除非集合保证随机访问性能,否则计算计数可能是 O(n) 操作。 developer.apple.com/documentation/swift/array/2949997-count
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    相关资源
    最近更新 更多