I am writing an iOS App in Swift 4.2
Response from server is a string with values separated by pipe character "|". It contains many rows of values. I want to split it into an array of subarrays.
Response example:
"001|apple|red|002|banana|yellow|003|grapes|purple"
For this example, the output should be an array containing 3 arrays of above fruits. If I use response.componentsSeparatedByString("|")
it will give me an array with 9 elements, which I don't want. If I take the above example into consideration, what I need is an array of 3 arrays further having 3 elements.
Expected Output:
[[001, "apple", "red"], [002, "banana", "yellow"], [003, "grapes", "purple"]]
With regex you could do something like this with thanks to OOPer's extension
Add a string extension that splits the string based on a regex pattern.
Then split your string based on the pattern
[0-9]{3}
3 numbers in a row.I tested this in a playground and got the following result:
If you decide you want to exclude the ID from the resulting arrays you can modify the extension return to the following:
This will switch the return range to use the
upperBound
instead oflowerBound
You can use String method enumerateSubstrings in range using byWords options, check if the string is an integer, if so append a new array with that string to the result otherwise append the word to the last result array:
|
characterIf you want persist
001
as well, then changeresult.append([])
toresult.append([String(string)])
:Important
This solution expect that your string will start with number or crash otherwise.
If you can't guaranteed that your string starts with number, that you need to manually check that array not empty in guard block.
If I got correct what you want to receive as a result, then this code would make what you want:
This will work if you know the expected size of resulting subarrays
You can also remove
.map(String.init)
from the last line if it's ok for you that array elements are of typeString.SubSequence
Basic way
Output:
Okay You can do it recursively
Output
Case 1 For Input
Case 2 For Input