Here is a general way to split and join the string:
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"))
For an extension with more keywords.
Extension could be like this:
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"]
This is not the fastest way but with a clear logic. keywords don't need to be ordered here. If you know the order , this method is slower than sequence tail recursive.