I have a string that is formatted like this: "XbfdASF;FBACasc|Piida;bfedsSA|XbbnSF;vsdfAs|"
Basiclly its an ID;ID| and then it repeats.
I have the first ID and I need to find it's partner Example: I have 'Piida' and I need to find the String that follows it after the ';' which is 'bfedsSA'
How do I do this?
The problem I am having is that the length of the IDs is dynamic so I need to get the index of '|' after the ID I have which is 'Piida' and then get the string that is between these indexes which in this case should be 'bfedsSA'.
There are many ways to do this, but the easiest is to split the string into an array using a separator.
If you know JavaScript, it's the equivalent of the
.split()
string method; Swift does have this functionality, but as you see there, it can get a little messy. You can extend String like this to make it a bit simpler. For completeness, I'll include it here:Now, you can call
.split()
on strings like this:So, what you should do first is split up your ID string into segments by your separator, which will be
|
, because that's how your IDs are separated:Now, you have a String array of your IDs that would look like this:
Your IDs are in the format
ID;VALUE
, so you can split them again like this:You can access the ID at index 0 of that array and the value at index 1.
Example: