0

I have an array of strings and I'd like to split that into two. An array containing the elements before the separator, and another one after it.

let sourceArray = ["items that", "are", "split", "by a string"]
// String that splits this array: "split"
// Expected output: [["items that", "are"], ["by a string"]]

I tried joining the array into a string and using .components(), but that removes the actual elements of the original array. Is there a way to do this using a built-in method or do I need to loop over it?

2 Answers 2

1

You can try

let sourceArray = ["items that", "are", "split", "by a string"]

let index = sourceArray.split(separator: "split").map { Array($0) }

print(index)
Sign up to request clarification or add additional context in comments.

2 Comments

op doesn't mention that use case at least we expect it has one separator
Easy fix is to use the extended version of the function: let singleSplit = sourceArray.split(separator: "split", maxSplits: 1, omittingEmptySubsequences: false)
0

You could do it this way :

var sourceArray = ["items that", "are", "split", "by a string"];
var array1 = [];
var array2 = [];
var firstArray = true;
for (var i = 0; i<sourceArray.lenght; i++){
   if (sourceArray[i]!=="split") {
      if (firstArray){
          array1.push(sourceArray[i]);
      }
      else {
          array2.push(sourceArray[i]);
      }
   }
   else {
      firstArray = false;
   }

}

At the end of the loop, just join the two arrays into a third one if you want it like that : [array1,array2].

3 Comments

This c++ code is very discouraged in swift , you should always utilize new high level functions as it will offer performant & compact code
Yes you're right, It's better to use the split method for example as you mentionned it. I just wanted to show another way to do it.
The question also specifically says without looping through the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.