将Swift字符串从a部分拆分为b部分?

时间:2019-01-12 22:15:19

标签: swift string substring

我正在寻找一种将整个文本分为2个或更多部分的方法。因此,如果我有以下代码: var Text =“成分\ n牛奶\ n糖\ n苏打水\ n信息\ n您需要添加更多的糖” var SplitPart1 =“” var SplitPart2 =“” 如何在“ SplitPart1”和“ SplitPart2”中将零件从“成分”转换为“信息”? 最后,我需要以下两个字符串: SplitPart1:配料\ n牛奶\ n糖\ n苏打\ n SplitPart2:信息\ n您需要添加更多糖

3 个答案:

答案 0 :(得分:2)

我进行了一些快速搜索,发现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

答案 1 :(得分:0)

以下是拆分和连接字符串的一般方法:

    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"]

这不是最快的方法,但有明确的逻辑。不需要在此处订购关键字。如果知道顺序,则此方法比序列尾递归要慢。

答案 2 :(得分:0)

提供的字符串只有这种格式,不能更改。下面是一些使其变得动态的尝试。您将获得拆分后的数组,可用于填充数据。

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)
    }
}